# 問題 D: 貨物運輸 (good)------------------------------思維(多源BFS)

10 2 3 3
1 1
8 8
1 5 1
2 3 3
6 7 2
1 2
2 2
6 8

29

``````#pragma GCC optimize(3,"Ofast","inline")
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> PII;
const int N=1009;
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
ll dist[N][N];
bool vis[N][N];
int n,m,k,d;
ll w[N*N];
struct node
{
int x,y;
} shop[N*N],ston[N*N];
int main()
{
memset(dist,0x3f,sizeof dist);
queue<PII> q;
scanf("%d %d %d %d",&n,&m,&k,&d);
for(int i=1;i<=m;i++)
{
scanf("%d %d",&shop[i].x,&shop[i].y);
dist[shop[i].x][shop[i].y]=0;
q.push({shop[i].x,shop[i].y});
}
for(int i=1;i<=k;i++)
{
scanf("%d %d",&ston[i].x,&ston[i].y);
scanf("%lld",&w[i]);
}
for(int i=1,x,y;i<=d;i++)
{
scanf("%d %d",&x,&y);
vis[x][y]=1;
}

while(q.size())
{

auto t= q.front();q.pop();
for(int i=0;i<4;i++)
{
int x=dx[i]+t.first;
int y=dy[i]+t.second;
if(x<1||x>n||y<1||y>n||vis[x][y]) continue;
if(dist[t.first][t.second]+1>=dist[x][y]) continue;
dist[x][y]=dist[t.first][t.second]+1LL;
q.push({x,y});
//vis[t.first][t.second]=1;
}

}
ll ans=0;
for(int i=1;i<=k;i++)
{
//	cout<<w[i]<<"  "<<dist[ston[i].x][ston[i].y]<<endl;;
ans=(ans+w[i]*dist[ston[i].x][ston[i].y]);
}
printf("%lld\n",ans);
}
``````