额,还是一个路径问题,不过这次是判断是否存在负权回路,这个直接用bellman ford 算法做就行了,只要松弛次数超过n次,则证明存在负权回路
这个在说benllman ford算法的时候解释的很详细了,不过现在不太敢用INT_MAX来表示最大的整数了,动不动就溢出了
#include<iostream> #define MAXINT 9999999 using namespace std; int n,m,w,dis[510]; struct Edge { int u,v,weight; }edge[5220]; void relax(int u, int v, int weight) { if(dis[v] > dis[u] + weight) dis[v] = dis[u] + weight; } bool Bellman_Ford() { for(int i=1; i<=n-1; ++i) for(int j=1; j<=2*m+w; ++j) relax(edge[j].u, edge[j].v, edge[j].weight); bool flag = 1; // 判断是否有负环路 for(int i=1; i<=2*m+w; ++i) if(dis[edge[i].v] > dis[edge[i].u] + edge[i].weight) { flag = 0; break; } return flag; } int main() { int cas; cin>>cas; while(cas--) { cin>>n>>m>>w; int i; for(i=1;i<=n;i++) dis[i]=MAXINT; dis[1]=0; for(i=1;i<m*2;i+=2) { cin>>edge[i].u>>edge[i].v>>edge[i].weight; edge[i+1].u=edge[i].v; edge[i+1].v=edge[i].u; edge[i+1].weight=edge[i].weight; } int a; for(int j=0;j<w;j++) { cin>>edge[i].u>>edge[i].v>>a; edge[i].weight=0-a; i++; } if(!Bellman_Ford()) cout<<"YES"<<endl; else cout<<"NO"<<endl; } return 0; }