Poj 3259 Wormholes (SPFA判負環)
阿新 • • 發佈:2019-01-23
題意:有n個點。一個點到另外一個點上需要時間,由有一些蟲洞,你穿過蟲洞,可以返回多少秒之前,問是否能無限返回。
題解:判斷負環=-=,spfa直接解決。
Select Code #include<cstring> #include<cstdio> #include<queue> #include<cmath> #include<algorithm> #include<iostream> using namespace std; const int maxn =550; const int maxm = 5550; const int INF = 1e9; struct Edge{ int to; int w; int next; }edge[maxm]; int head[maxn]; int mark[maxn]; int vis[maxn]; int dis[maxn]; int tol; int n,m,k; void add(int u,int v,int w){ edge[tol].to = v; edge[tol].w = w; edge[tol].next = head[u]; head[u] = tol++; } bool spfa(){ for(int i = 1 ; i <= n ; i++){ mark[i] = 0; dis[i] = INF; vis[i] = 0; } queue<int> q; q.push(1); dis[1] = 0; vis[1] = 1; mark[1] = 1; while(!q.empty()){ int u = q.front(); q.pop(); mark[u] = 0; for(int i = head[u] ; i != -1 ; i = edge[i].next){ int v = edge[i].to; if(dis[v] > dis[u] + edge[i].w){ dis[v] = dis[u] + edge[i].w; if(!mark[v]){ mark[v] =1; vis[v]++; q.push(v); if(vis[v] >= n){ return true; } } } } } return false; } int main(){ int z; cin >> z; while(z--){ memset(head,-1,sizeof(head)); tol = 0; cin >> n >> m >> k; while(m--){ int u,v,w; cin >> u >> v >> w; add(u,v,w); add(v,u,w); } while(k--){ int u,v,w; cin >> u >> v >> w; add(u,v,-w); } if(spfa()) cout << "YES" << endl; else cout << "NO" << endl; } }