问题描述
栋栋最近开了一家餐饮连锁店,提供外卖服务。随着连锁店越来越多,怎么合理的给客户送餐成为了一个急需解决的问题。
栋栋的连锁店所在的区域可以看成是一个n×n的方格图(如下图所示),方格的格点上的位置上可能包含栋栋的分店(绿色标注)或者客户(蓝色标注),有一些格点是不能经过的(红色标注)。
方格图中的线表示可以行走的道路,相邻两个格点的距离为1。栋栋要送餐必须走可以行走的道路,而且不能经过红色标注的点。

送餐的主要成本体现在路上所花的时间,每一份餐每走一个单位的距离需要花费1块钱。每个客户的需求都可以由栋栋的任意分店配送,每个分店没有配送总量的限制。
现在你得到了栋栋的客户的需求,请问在最优的送餐方式下,送这些餐需要花费多大的成本。
输入格式
输入的第一行包含四个整数n, m, k, d,分别表示方格图的大小、栋栋的分店数量、客户的数量,以及不能经过的点的数量。
接下来m行,每行两个整数xi, yi,表示栋栋的一个分店在方格图中的横坐标和纵坐标。
接下来k行,每行三个整数xi, yi, ci,分别表示每个客户在方格图中的横坐标、纵坐标和订餐的量。(注意,可能有多个客户在方格图中的同一个位置)
接下来d行,每行两个整数,分别表示每个不能经过的点的横坐标和纵坐标。
输出格式
输出一个整数,表示最优送餐方式下所需要花费的成本。
样例输入
10 2 3 3
1 1
8 8
1 5 1
2 3 3
6 7 2
1 2
2 2
6 8
样例输出
29
评测用例规模与约定
前30%的评测用例满足:1<=n <=20。
前60%的评测用例满足:1<=n<=100。
所有评测用例都满足:1<=n<=1000,1<=m, k, d<=n^2。可能有多个客户在同一个格点上。每个客户的订餐量不超过1000,每个客户所需要的餐都能被送到。
解题方案:
广度优先搜索,从饭店出发寻找客户
ps:程序运行超时,在CCF系统中得分80分,
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
// 地图数组
static int[][] map = new int[1001][1001];
// 标记数组
static boolean[][] mark = new boolean[1001][1001];
public static class Node {
public int x;
public int y;
public int t;
public Node(int x, int y, int t) {
this.x = x;
this.y = y;
this.t = t;
}
}
public static Queue<Node> queue = new LinkedList<Node>();
public static int[][] dir = { {0,1},
{1,0},
{-1,0},
{0,-1}
};
static int n,m,k,d;
public static long bfs(){
long ans = 0;
int cnt = 0;
while(!queue.isEmpty()){
Node node = queue.poll();
// 依次扩展器相邻4个结点
for(int i = 0;i < 4;i ++){
int nx = node.x + dir[i][0];
int ny = node.y + dir[i][1];
if(nx <= 0 || nx > n || ny <= 0 || ny > n){
continue;
}
if(map[nx][ny] == -1) continue;
if(mark[nx][ny]) continue;
// 新的状态
Node node2 = new Node(nx, ny, node.t + 1);
queue.add(node2);
mark[nx][ny] = true;
if(map[nx][ny] > 0){
ans = ans + map[nx][ny] * node2.t;
cnt ++;
if(cnt == k) return ans;
}
}
}
return ans;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
m = scanner.nextInt();
k = scanner.nextInt();
d = scanner.nextInt();
for(int i =0;i < m; i ++) {
int x = scanner.nextInt();
int y = scanner.nextInt();
queue.add(new Node(x,y,0));
map[x][y] = -1;
}
// 值大于0表示该点为客户位置
for(int i = 0;i < k; i ++){
int x = scanner.nextInt();
int y = scanner.nextInt();
int f = scanner.nextInt();
map[x][y] += f;
}
// -1 表示该点不可以通过
for(int i =0; i < d; i ++){
int x = scanner.nextInt();
int y = scanner.nextInt();
map[x][y] = -1;
}
System.out.println(bfs());
}
}