使用bfs求解(运行超时,80分)
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Node{
public int x;
public int y;
public int step;
public Node(int x, int y, int step) {
this.x = x;
this.y = y;
this.step = step;
}
}
public class Main{
private static int n;
private static int totalCount;
private static Queue<Node> queue = new LinkedList<>();
private static int[][] counts;
private static boolean[][] visited;
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String[] firstLine = scanner.nextLine().split(" ");
n = Integer.parseInt(firstLine[0]);
int m = Integer.parseInt(firstLine[1]);
int k = Integer.parseInt(firstLine[2]);
int d = Integer.parseInt(firstLine[3]);
visited = new boolean[n + 1][n + 1];
counts = new int[n + 1][n + 1];
for(int i = 0; i < m; i++){
String[] line = scanner.nextLine().split(" ");
int x = Integer.parseInt(line[0]);
int y = Integer.parseInt(line[1]);
visited[x][y] = true;
queue.add(new Node(x, y, 0));
}
for(int i = 0; i < k; i++){
String[] line = scanner.nextLine().split(" ");
int x = Integer.parseInt(line[0]);
int y = Integer.parseInt(line[1]);
int c = Integer.parseInt(line[2]);
if(counts[x][y] == 0)
totalCount++;
counts[x][y] += c;
}
for(int i = 0; i < d; i++){
String[] line = scanner.nextLine().split(" ");
int x = Integer.parseInt(line[0]);
int y = Integer.parseInt(line[1]);
visited[x][y] = true;
}
scanner.close();
System.out.println(bfs());
}
private static long bfs(){
long step = 0;
int[][] dirs = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
while (!queue.isEmpty()){
if(totalCount == 0)
return step;
Node front = queue.poll();
for(int i = 0; i < dirs.length; i++){
int x = front.x + dirs[i][0];
int y = front.y + dirs[i][1];
if(x < 1 || x > n || y < 1 || y > n)
continue;
if(visited[x][y])
continue;
visited[x][y] = true;
Node node = new Node(x, y, front.step + 1);
queue.add(node);
if(counts[x][y] > 0){
totalCount--;
step += counts[x][y] * node.step;
if(totalCount == 0)
return step;
}
}
}
return step;
}
}