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

半年之后再看这道题,感觉果然不一样……

Posted by Ruby931031 at 2012-07-12 00:41:09 on Problem 3259
In Reply To:关于Bellman-Ford算法的bug Posted by:Ruby931031 at 2012-03-21 17:49:36
//只要加一个超级源点0连接到各个顶点且权值为0就好了。。半年时间,天差地别。
//使用链式前向星+Bellman-Ford,时间短了一半还多!!
//3259 Accepted 464K 360MS G++ 1471B 2012-07-12 00:34:41 
//3259 Accepted 1172K 891MS C++ 1047B 2012-03-21 17:24:07 

#include <stdio.h>
#include <string.h>
#define MAXN 800
#define MAXM 3000
#define INF (1<<30)

struct Edge{
	int to,next,w;
} edge[MAXM<<1];
int head[MAXN],dist[MAXN],n,m,w;

bool BellmanFord(){
	int i,j,k;
	for (i=1; i<=n; ++i)	dist[i]=INF;
	dist[0]=0;
	for (i=1; i<n; ++i)			//松弛n-1轮
		for (j=0;j<=n; ++j)
			for (k=head[j]; k!=-1; k=edge[k].next)
				if ( dist[edge[k].to] > dist[j] + edge[k].w )		dist[edge[k].to] = dist[j] + edge[k].w;

	for (j=0; j<=n; ++j)			//若仍能进行松弛,说明存在负权回路
		for (k=head[j]; k!=-1; k=edge[k].next)
			if ( dist[edge[k].to] > dist[j] + edge[k].w )
				return true;
	return false;

}

int main()
{
	int f,i,s,e,t,tot;
	scanf("%d",&f);
	while (f--){
		memset(head,-1,sizeof(head));
		scanf("%d %d %d", &n, &m, &w);
		for (tot=0; tot<n; ++tot){	//加入超级源点0和图中每一点相连且边权值为0
			edge[tot].to = tot+1;
			edge[tot].w = 0;
			edge[tot].next = head[0];
			head[0] = tot;
		}
		for (i=0; i<m; ++i){		//读入普通边
			scanf("%d %d %d", &s, &e, &t);
			edge[tot].to = e;		//无向边存两遍
			edge[tot].w = t;
			edge[tot].next = head[s];
			head[s] = tot++;

			edge[tot].to = s;
			edge[tot].w = t;
			edge[tot].next = head[e];
			head[e] = tot++;
		}
		for (i=0; i<w; ++i){		//读入虫洞
			scanf("%d %d %d", &s, &e, &t);
			edge[tot].to = e;
			edge[tot].w = -t;
			edge[tot].next = head[s];
			head[s] = tot++;
		}
		if ( BellmanFord() )		printf("YES\n");		//对超级源点0调用BF算法
		else	printf("NO\n");
	}
	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