"POJ 3259" wormholes
Judging negative ring--BELLMAN/SPFA
The code is as follows
Bellman-ford
#include <cstdio>#include <cstring>#define INF 0x3f3f3f3fusing namespace STD;typedef structedge{intU,v,w;} Edge; Edge eg[5555];intdis[555],N,TP;BOOLBellMan () {memset(Dis,inf,sizeof(dis)); dis[1] =0;intI,j,u,v,w; for(i =1; I < n; ++i) { for(j =0; J < TP; ++J) {u = eg[j].u; v = eg[j].v; W = EG[J].W;if(Dis[u] < INF && Dis[u] + W < Dis[v]) dis[v] = Dis[u] + W; } } for(j =0; J < TP; ++J) {u = eg[j].u; v = eg[j].v; W = EG[J].W;if(Dis[u] < INF && Dis[u] + W < dis[v])return 1; }return 0;}voidADD (intUintVintW) {eg[tp].v = u; eg[tp].u = v; EG[TP++].W = w;}intMain () {intT,i,m,u,v,w,k,temp;scanf("%d", &t); while(t--) {TP =0;scanf(" %d%d%d", &n,&m,&k); while(m--) {scanf(" %d%d%d", &u,&v,&w); ADD (U,V,W); ADD (V,U,W); } while(k--) {scanf(" %d%d%d", &u,&v,&w); ADD (U,V,-W); }printf("%s\n", BellMan ()?"YES":"NO"); }return 0;}
Spfa
#include <cstdio>#include <queue>#include <cstring>using namespace STD;typedef structedge{intV,w,next;} Edge; Edge eg[66666];inthead[555];intdis[555],n,in[555];BOOLvis[555];intTpBOOLSPFA () {memset(dis,-1,sizeof(dis));memset(Vis,0,sizeof(VIS));memset(In,0,sizeof(in)); Queue <int>Q Q.push (1); dis[1] =0;intI,u,v,w; while(!q.empty ()) {u = Q.front (); Q.pop (); Vis[u] =0; for(i = head[u]; I! =-1; i = eg[i].next) {v = eg[i].v; W = EG[I].W;if(Dis[v] = =-1|| DIS[V] > Dis[u] + W) {Dis[v] = Dis[u] + W;if(!vis[v]) {in[v]++;if(In[v] = = N)return 1; VIS[V] =1; Q.push (v); } } } }return 0;}voidADD (intUintVintW) {eg[tp].next = Head[u]; EG[TP].V = v; EG[TP].W = W; Head[u] = tp++;}intMain () {intT,i,m,k,w,u,v;scanf("%d", &t); while(t--) {scanf(" %d%d%d", &n,&m,&k);memset(head,-1,sizeof(head)); while(m--) {scanf(" %d%d%d", &u,&v,&w); ADD (U,V,W); ADD (V,U,W); } while(k--) {scanf(" %d%d%d", &u,&v,&w); ADD (U,V,-W); }printf("%s\n", SPFA ()?"YES":"NO"); }return 0;}
"POJ 3259" wormholes