Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
Bellman Ford 判断负环AC (附代码)//ACCEPTED! Bellman Ford · #include<iostream> #include<cstdio> #include<cstring> #define INF 999999 using namespace std; int F,N,M,W; int s,e,t; int cnt; int dis[520]; struct Edge { int u,v; int cost; // u go to v costs 'cost' }edge[5040]={0}; void addedge(int ss,int ee,int tt) { edge[cnt].u=ss; edge[cnt].v=ee; edge[cnt].cost=tt; cnt++;//count of edges } int Bellman() { for(int i=1;i<=N;i++) dis[i]=INF; dis[1]=0; for(int i=1;i<N;i++) for(int j=0;j<cnt;j++) dis[edge[j].v]=min(dis[edge[j].v],(dis[edge[j].u]+edge[j].cost)); for(int j=0;j<cnt;j++) if(dis[edge[j].v]>dis[edge[j].u]+edge[j].cost) return 0; return 1; } int main() { cin>>F; for(int k=1;k<=F;k++) { cin>>N>>M>>W; cnt=0; for(int i=1;i<=M;i++) { cin>>s>>e>>t; addedge(s,e,t); addedge(e,s,t); } for(int i=1;i<=W;i++) { cin>>s>>e>>t; addedge(s,e,-t); } if(Bellman()) cout<<"NO"<<endl; else cout<<"YES"<<endl; } return 0; } Followed by:
Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator