Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

Bellman Ford 判断负环AC (附代码)

Posted by MadCreeper at 2017-05-18 22:11:06 on Problem 3259
//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:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator