欢迎访问我的CCF认证解题目录
题目描述
思路过程
最短路径的变形题,有多个起始点,需要计算出距离最近的起始点,采用BFS遍历即可。
注意:多个起始点一起压入队列,否则可能会超时
代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] line = br.readLine().split(" ");
int n = Integer.parseInt(line[0]), m = Integer.parseInt(line[1]);
int k = Integer.parseInt(line[2]), d = Integer.parseInt(line[3]);
int[][] graph = new int[n+1][n+1];//到达每个点的最小花费
int[][] way = {{0,1}, {1,0}, {0,-1}, {-1,0}};//方向
int INF = Integer.MAX_VALUE;//未访问的初始值
Node[] buys = new Node[k];//客户
LinkedList<Node> q = new LinkedList<Node>();//队列
//初始化图
for ( int i = 1; i <= n; i++ ) {
for ( int j = 1; j <= n; j++ ) {
graph[i][j] = INF;
}
}
//读入商店
for ( int i = 0; i < m; i++ ) {
line = br.readLine().split(" ");
int x = Integer.parseInt(line[0]), y = Integer.parseInt(line[1]);
q.add(new Node(x,y));
graph[x][y] = 0;
}
//读入买家
for ( int i = 0; i < buys.length; i++ ) {
line = br.readLine().split(" ");
buys[i] = new Node(Integer.parseInt(line[0]), Integer.parseInt(line[1]), Integer.parseInt(line[2]));
}
//标记不能访问的点
for ( int i = 0; i < d; i++ ) {
line = br.readLine().split(" ");
graph[Integer.parseInt(line[0])][Integer.parseInt(line[1])] = -1;
}
//BFS
while ( !q.isEmpty() ) {
Node temp = q.remove(0);
for ( int j = 0; j < way.length; j++ ) {
int r = temp.r+way[j][0], c = temp.c+way[j][1];
//不越界,能访问且能优化
if ( r > 0 && r <= n && c > 0 && c <= n && graph[r][c] != -1 && graph[temp.r][temp.c]+1 < graph[r][c] ) {
graph[r][c] = graph[temp.r][temp.c]+1;
q.add(new Node(r, c));
}
}
}
long sum = 0;
for ( int i = 0; i < k; i++ ) {
sum += graph[buys[i].r][buys[i].c]*buys[i].cnt;
}
System.out.println(sum);
}
}
class Node{
int r, c, cnt;
public Node(int r, int c) {
this.r = r;
this.c = c;
}
public Node(int r, int c, int cnt) {
this.r = r;
this.c = c;
this.cnt = cnt;
}
}