这是一个多源最短路问题
code
记得关同步,不然会超时
#include<bits/stdc++.h>
using namespace std;
#define x first
#define y second
typedef pair<int, int>PII;
typedef long long LL;
const int N = 1010;
int dist[N][N];bool st[N][N];
int n, m, k, d;
queue<PII>q;
struct
{
int x,y,c;
}tg[N*N];
int dx[]={-1,0,1,0},dy[]={0,1,0,-1};
void bfs()
{
while(q.size())
{
PII t=q.front();
q.pop();
for(int i=0;i<4;i++)
{
int tx=t.x+dx[i],ty=t.y+dy[i];
if(tx<1||tx>n||ty<1||ty>n||st[tx][ty])continue;
if(dist[tx][ty]>dist[t.x][t.y]+1) //当前位置比上个位置距离远
{
dist[tx][ty]=dist[t.x][t.y]+1; //更新一下距离
q.push({tx,ty});
}
}
}
}
int main()
{
cin.tie(nullptr)->sync_with_stdio(false);
cin>>n>>m>>k>>d;
memset(dist,0x3f,sizeof dist); //因为要求最短距离所以要初始化为最大值
while(m--)
{
int x,y;cin>>x>>y;
dist[x][y]=0; //刚开始每个店到自己的距离都初始化为0
q.push({x,y}); //分店加入队列,后面BFS搜每个分店到客户的距离
}
for(int i=0;i<k;i++)
{
cin>>tg[i].x>>tg[i].y>>tg[i].c;
}
while(d--)
{
int x,y;cin>>x>>y;
st[x][y]=true; //墙体标记为不能走
}
bfs();
//计算到达k个客户的所有最短路之和
LL res=0;
for(int i=0;i<k;i++)
res+=dist[tg[i].x][tg[i].y]*tg[i].c;
cout<<res<<endl;
return 0;
}