title Link:http://poj.org/problem?id=3259
Test Instructions:n farms, M bidirectional path, W one-way path (wormhole). The one-way wormhole path is negative. The farmer wants to know if he can see himself (X).
In fact , just started not to read too test instructions. Then in fact if he can see himself, it means that a negative ring has been formed through the wormhole. That is, through the SPFA to find negative ring (negative power loop). The judgment here is to add a cnt[] array to record the number of times the point is enqueued, greater than or equal to n indicates that a negative ring has been formed.
Code:
1#include <iostream>2#include <cstdio>3#include <stack>4#include <vector>5#include <queue>6#include <algorithm>7 using namespacestd;8 Const intMAXN = 2e5+7;9 Const intINF =0xFFFFFF;Tenvector< pair<int,int> >E[MAXN]; One A intn,m,w; - intD[MAXN],INQ[MAXN]; - intCNT[MAXN]; the - voidinit () { - for(inti =0; I <= N; i++) - e[i].clear (); + } - + voidSPFA () { A for(inti =0; I <= N; i++) atInq[i] =0, d[i] = inf,cnt[i] =0; -queue<int>Q; -Q.push (1); -d[1] =0; -inq[1] =1; -cnt[1] =1; in while( !Q.empty ()) { - intU =Q.front (); to Q.pop (); +Inq[u] =0; - for(inti =0; I < e[u].size (); i++){ the intv =E[u][i].first; * intval =E[u][i].second; $ if(D[v] > D[u] +val) {Panax NotoginsengD[V] = D[u] +Val; - if(Inq[v] = =0){ thecnt[v]++; +INQ[V] =1; A if(Cnt[v] >= N) {//determine a bit more than the total number of vertices, there is a negative ring theprintf"yes\n"); + return; - } $ Q.push (v); $ } - } - } the - }Wuyiprintf"no\n"); the } - intMain () { Wu intF; -Cin>>F; About while(f--){ $Cin>>n>>m>>W; - init (); - //two-way positive right - intx, y, z A for(inti =1; I <= m; i++){ +Cin>>x>>y>>Z; the E[x].push_back (Make_pair (y,z)); - E[y].push_back (Make_pair (x,z)); $ } the //one-way negative right the for(inti =1; I <= W; i++){ theCin>>x>>y>>Z; theE[x].push_back (Make_pair (y,-z)); - } in SPFA (); the } the About return 0; the}
"POJ" 3259 wormholes