【SPFA】2020牛客NOIP赛前集训营-普及组(第六场)D-自由世界


FORM 1 TO n
跑spfa。对于传送点,和当前点一并加入到队列中,并把他们的最短路赋值为0。


代码

#include<cstdio>
#include<queue>
#include<cstring>
#include<iostream>
using namespace std;
int n,m,k,ans,t,u,v,zz,dis[3000],ifcsd[3000],csd[3000],l[3000];
bool in[3000];
struct asdf{
	int to,z,next;
} A[100001];
void spfa(int d){
	memset(dis,0x7f,sizeof(dis));
	queue<int> Q;
	Q.push(d);
	for(int i = 1; i <= k; ++i){
		dis[csd[i]] = 0;
		in[csd[i]] = 1;
		Q.push(csd[i]);
	}
	in[d] = 1;
	dis[d] = 0;
	while(Q.size() > 0){
		int now = Q.front();
		Q.pop();
		for(int i = l[now]; i; i = A[i].next){
			if(dis[now] + A[i].z < dis[A[i].to]){
		 	  dis[A[i].to] = dis[now] + A[i].z;
		 	  if (!in[A[i].to]){
		 	  	in[A[i].to] = 1;
		 	  	Q.push(A[i].to);
			   }
		    }
		}
		in[now] = 0;
	}
}

int main(){
	scanf("%d%d%d",&n,&m,&k);
	for(int i = 1; i <= m; ++i) {
		scanf("%d%d%d",&u,&v,&zz);
		A[++t] = (asdf){v,zz,l[u]}; l[u] = t;
		A[++t] = (asdf){u,zz,l[v]}; l[v] = t;
	}
	for(int i = 1; i <= k; ++i){
		scanf("%d",&csd[i]);
		ifcsd[csd[i]] = 1;
	}
    for(int i = 1; i < n; ++i)
	if(!ifcsd[i+1]){
        spfa(i);
        ans = ans + dis[i+1];
	}
    printf("%d",ans);
}  
版权声明:本文为qq_42937087原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_42937087/article/details/109428930