Wormholes POJ - 3259
考察:bf或者spfa判断负环
应该是负环判断的入门题.这道题记录一下bf算法判断负环的模板.万一以后要用呢~
注释基本写在代码里
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 using namespace std;//bf算法判断负环的模板 5 const int N = 510; 6 const int M = 2510; 7 int dist[N],n,m,t,cnt;//backup数组用于存储第几次 的最短路 8 struct Edge{ 9 int s,e,w; 10 }edge[M<<1]; 11 bool bellmanford() 12 { 13 memset(dist,0x3f,sizeof dist); 14 for(int i=1;i<=n-1;i++){ 15 bool flag = true; 16 for(int j=1;j<=cnt;j++){//无所谓谁起点,只要存在负环那么值一定会被不断更新 17 int a = edge[j].s,b = edge[j].e,w=edge[j].w; 18 if(dist[b]>dist[a]+w) { 19 dist[b] = min(dist[b],dist[a]+w); 20 flag = false; 21 } 22 } 23 if(flag) break; 24 } 25 for(int j=1;j<=cnt;j++){//出来后再检查一次 26 int a = edge[j].s,b = edge[j].e,w=edge[j].w; 27 if(dist[b]>dist[a]+w) return true; 28 } 29 return false; 30 } 31 int main() 32 { 33 // freopen("in.txt","r",stdin); 34 int T; 35 scanf("%d",&T); 36 while(T--) 37 { 38 cnt = 0; 39 scanf("%d%d%d",&n,&m,&t); 40 for(int i=1;i<=m*2;i+=2) 41 { 42 int x,y,z; 43 scanf("%d%d%d",&x,&y,&z); 44 edge[i] = {x,y,z}; 45 edge[i+1] = {y,x,z}; 46 cnt+=2; 47 } 48 for(int i=cnt+1;i<=m*2+t;i++){ 49 int x,y,z; 50 scanf("%d%d%d",&x,&y,&z); 51 edge[i] = {x,y,-z}; 52 cnt++; 53 } 54 if(bellmanford()) puts("YES"); 55 else puts("NO"); 56 } 57 return 0; 58 }