很正常的多源dfs,就是数据读起来有点麻烦,直接贴代码了
Java代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static int[][] add = {{-1,0},{1,0},{0,-1},{0,1}};
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String s = bf.readLine();
String[] split = s.split(" ");
int n = Integer.parseInt(split[0]);
int m = Integer.parseInt(split[1]);
int k = Integer.parseInt(split[2]);
int d = Integer.parseInt(split[3]);
int[][] g = new int[n+1][n+1];
int[][] flag = new int[n+1][n+1];
List<Gav> list = new ArrayList<>();
for (int i = 0; i < m; i++) {
String s1 = bf.readLine();
String[] split1 = s1.split(" ");
int x = Integer.parseInt(split1[0]);
int y = Integer.parseInt(split1[1]);
flag[x][y] = -1;//标记分店位置
list.add(new Gav(x,y));
}
for (int i = 0; i < k; i++) {
String s1 = bf.readLine();
String[] split1 = s1.split(" ");
int x = Integer.parseInt(split1[0]);
int y = Integer.parseInt(split1[1]);
int count = Integer.parseInt(split1[2]);
g[x][y] += count;
}
for (int i = 0; i < d; i++) {
String s1 = bf.readLine();
String[] split1 = s1.split(" ");
int x = Integer.parseInt(split1[0]);
int y = Integer.parseInt(split1[1]);
flag[x][y] = -1;
}
bf.close();
//分店和不能走的格子都被标记成了-1
int level = 0;
LinkedList<Gav> queue = new LinkedList<>();
Gav last = list.get(m-1);
Gav scan = null;
for (int i = 0; i < m; i++) {
queue.add(list.get(i));
}
long res = 0;
while (!queue.isEmpty()) {
Gav poll = queue.poll();
int x = poll.x;
int y = poll.y;
res = res + g[x][y] * level;
for (int i = 0; i < 4; i++) {
int nx = x + add[i][0];
int ny = y + add[i][1];
if (nx > 0 && ny > 0 && nx <= n && ny <= n && flag[nx][ny] != -1) {
flag[nx][ny] = -1;
scan = new Gav(nx, ny);
queue.add(scan);
}
}
if (poll.equals(last)) {
level++;
last = scan;
}
}
System.out.println(res);
}
static class Gav{
int x;
int y;
public Gav(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Gav gav = (Gav) o;
return x == gav.x &&
y == gav.y;
}
}
}