POJ 3259 Wormholes
这题是一个模版题,可以借助bellman-ford算法中的判断负环的办法解决。
既然是模版题不多说上模版:
#include <stdio.h> #define typec int // type of cost const typec inf=0x3f3f3f3f; // max of cost const int V=505; const int E=8000; int n, m, pre[V], edge[E][3]; typec dist[V]; int relax (int u, int v, typec c) { if (dist[v] > dist[u] + c) { dist[v] = dist[u] + c; pre[v] = u; return 1; } return 0; } int bellman (int src) { int i, j; for (i=0; i<n; ++i) { dist[i] = inf; pre[i] = -1; } dist[src] = 0; bool flag; for (i=1; i<n; ++i) { flag = false; for (j=0; j<m; ++j) { if( 1 == relax(edge[j][0], edge[j][1], edge[j][2]) ) flag = true; } if( !flag ) break; } for (j=0; j<m; ++j) { if (1 == relax(edge[j][0], edge[j][1], edge[j][2])) return 0; //如果是负环返回0. } return 1; } int main() { int F,M,W,u,v,w,i,j; scanf("%d",&F); while(F--) { scanf("%d%d%d",&n,&M,&W); m=0; for(i=0;i<M;i++) { scanf("%d%d%d",&edge[m][0],&edge[m][1],&edge[m][2]); m++; edge[m][0]=edge[m-1][1]; edge[m][1]=edge[m-1][0]; edge[m][2]=edge[m-1][2]; m++; } for(i=0;i<W;i++) { scanf("%d%d%d",&u,&v,&w); w=-w; for(j=0;j<m;j++) { if(edge[i][0]==u&&edge[i][1]==v&&edge[i][2]>w) { edge[i][2]=w; break; } } if(j==m) { edge[m][0]=u; edge[m][1]=v; edge[m][2]=w; m++; } } if(bellman(1)) { printf("NO\n"); } else { printf("YES\n"); } } return 0; }