棟棟的連鎖店所在的區域可以看成是一個n×n的方格圖(如下圖所示),方格的格點上的位置上可能包含棟棟的分店(綠色標註)或者客戶(藍色標註),有一些格點是不能經過的(紅色標註)。
方格圖中的線表示可以行走的道路,相鄰兩個格點的距離爲1。棟棟要送餐必須走可以行走的道路,而且不能經過紅色標註的點。
送餐的主要成本體現在路上所花的時間,每一份餐每走一個單位的距離需要花費1塊錢。每個客戶的需求都可以由棟棟的任意分店配送,每個分店沒有配送總量的限制。
現在你得到了棟棟的客戶的需求,請問在最優的送餐方式下,送這些餐需要花費多大的成本。
#define MAX_SIZE 1000+5
#define INF 0x3f3f3f3f
#include<iostream>
#include<stack>
#include<string.h>
#include<queue>
using namespace std;
int map[MAX_SIZE][MAX_SIZE];
int cusMap[MAX_SIZE][MAX_SIZE];
int mmp[MAX_SIZE][MAX_SIZE];
const int dir[4][2] = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };
struct po{
int x, y, step;
};
queue<po> poi;
int n, m, k, d;
int fg[MAX_SIZE][MAX_SIZE];
void bfs(){
memset(fg, 0, sizeof(fg));
while (!poi.empty()){
po p = poi.front(); poi.pop();
for (int i = 0; i < 4; i++){
int nx = p.x + dir[i][0];
int ny = p.y + dir[i][1];
if (nx > 0 && ny > 0 && nx <= n && ny <= n && map[nx][ny] >= 0){
po nnp; nnp.x = nx; nnp.y = ny; nnp.step = p.step + 1;
if (mmp[nx][ny] > nnp.step){
mmp[nx][ny] = nnp.step;
poi.push(nnp);
}
fg[nx][ny] = 1;
}
}
}
}
int main(){
cin >> n >> m >> k >> d;
for (int i = 0; i < m; i++){
int x, y;
cin >> x >> y;
po p; p.x = x; p.y = y; p.step = 0;
poi.push(p); mmp[x][y] = 0;
}
for (int i = 0; i < k; i++){
int x, y, c;
cin >> x >> y >> c;
cusMap[x][y] += c;
}
for (int i = 0; i < d; i++){
int x, y;
cin >> x >> y;
map[x][y] = -1;
}
long long ans = 0;
memset(mmp, INF, sizeof(mmp));
bfs();
for (int i = 1; i <= n; i++){
for (int j = 1; j <= n; j++){
if (cusMap[i][j] > 0){
ans += cusMap[i][j] * mmp[i][j];
}
}
}
cout << ans << endl;
return 0;
}