注意 变量的范围 要取long类型
package csp2014_9_4;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import org.w3c.dom.css.ViewCSS;
public class Main {
long[][]map;
boolean [][]visit;
int n, m, k, d;
int [][]dir = {{0,1},{0,-1},{1,0},{-1,0}};
long ans;
LinkedList<Node> que;
public static void main(String[] args) {
new Main().run();
}
public void run() {
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
n = in.nextInt();
m = in.nextInt();
k = in.nextInt();
d = in.nextInt();
que = new LinkedList<>();
visit = new boolean[n+1][n+1];
map = new long[n+1][n+1];
for(int i = 0; i < m; i++ ) {
int x = in.nextInt();
int y = in.nextInt();
que.offer(new Node(x, y, 0));
}
for(int i = 0; i < k; i++ ) {
int x = in.nextInt();
int y = in.nextInt();
long num = in.nextInt();
map[x][y] = num;
}
for(int i = 0; i < d; i++ ) {
int x = in.nextInt();
int y = in.nextInt();
visit[x][y] = true;
}
ans = 0;
bfs();
System.out.println(ans);
}
}
public void bfs() {
int cnt = 0;
while(!que.isEmpty()) {
Node node = que.poll();
for(int i = 0; i < 4; i++ ) {
int xx = node.x + dir[i][0];
int yy = node.y + dir[i][1];
if(xx>0&&yy>0&&xx<=n&&yy<=n&&!visit[xx][yy]) {
visit[xx][yy] = true;
ans += (node.step+1)*map[xx][yy];
Node tmp = new Node(xx, yy, node.step+1);
que.offer(tmp);
}
}
}
}
}
class Node{
int x, y;
long mum;
long step;
public Node(int x, int y, long s) {
step = s;
this.x = x;
this.y = y;
}
}
上面 可以在达到目标后提前终止
if(map[xx][yy] != 0) {
ans += (node.step+1)*map[xx][yy];
cnt++;
if(cnt == k)
return;
}