poj 3259Wormholes (spfa最短路径)

时间:2021-01-06 09:03:16
#include<stdio.h>
#include<string.h>
#include<limits.h>
#include<queue>
using namespace std;
#define N 5505
#define M 55000//注意边和点集的数组大小
struct edge
{
int to,value,next;
}edges[M];
int heads[N],len=;
int addedge(int u,int v,int w)
{
edges[len].to=v,edges[len].value=w,edges[len].next=heads[u];
heads[u]=len++;
return ;
}
int n,m; int spfa(int v)
{
queue<int> q;
int inqueue[N],dis[N];
memset(inqueue,,sizeof(inqueue)),inqueue[v]=;
q.push(v);
for(int i=;i<n;i++) dis[i]=INT_MAX;
dis[v]=;
int times[N];
memset(times,,sizeof(times)),times[v]=; while(!q.empty()){
int x=q.front();
q.pop();
inqueue[x]=;
for(int j=heads[x];j!=-;j=edges[j].next){
int to=edges[j].to,value=edges[j].value;
if(value+dis[x]<dis[to]){
dis[to]=value+dis[x];
if(!inqueue[to]){ //注意已经在队列里面的不用再加入队列
if(++times[to]>=n) return ;
inqueue[to]=,q.push(to);
}
}
}
}
return ;
}
int main(void)
{
int i,j,t;
int a,b,c;
scanf("%d",&t);
while(t--){
int w;
memset(heads,-,sizeof(heads));//注意不要忘记
scanf("%d%d%d",&n,&m,&w);
while(m--){
scanf("%d%d%d",&a,&b,&c);
addedge(a-,b-,c);
addedge(b-,a-,c); }
while(w--){
scanf("%d%d%d",&a,&b,&c);
addedge(a-,b-,-c);
}
if(!spfa()) printf("YES\n");
else printf("NO\n");
} }