POJ--3259 Wormholes (SPFA判负环)
题目电波 3259 Wormholes
#include<iostream> #include<cstring> #include<algorithm> #include<queue> #include<stdio.h> using namespace std; #define maxn 100010 #define inf 0x3f3f3f3f struct ac{ int to,va; ac(){} ac(int a,int b){ to=a,va=b; } }; vector<ac>q[maxn]; int dis[maxn],vis[maxn]; bool fa[maxn]; int n,m,s; void init(){ for(int j=1;j<=maxn;j++) q[j].clear(); } bool spfa(){ memset(vis,0,sizeof(vis)); memset(fa,0,sizeof(fa)); memset(dis,inf,sizeof(dis)); dis[1]=0; queue<int>pq; pq.push(1); while(!pq.empty()){ int u=pq.front(); pq.pop(); fa[u]=0; for(int j=0;j<q[u].size();j++){ int v=q[u][j].to; int va=q[u][j].va; if(dis[v]>dis[u]+va){ dis[v]=dis[u]+va; if(!fa[v]){ fa[v]=1; vis[v]++; pq.push(v); if(vis[v]>=n){ return 1; } } } } } return 0; } int main(){ int t; cin>>t; while(t--){ init(); cin>>n>>m>>s; for(int j=0;j<m;j++){ int u,v,va; scanf("%d%d%d",&u,&v,&va); q[u].push_back(ac(v,va)); q[v].push_back(ac(u,va)); } for(int j=0;j<s;j++){ int u,v,va; scanf("%d%d%d",&u,&v,&va); q[u].push_back(ac(v,-va)); } if(spfa()){ cout<<"YES"<<endl; }else{ cout<<"NO"<<endl; } } }