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

用边O(n*m)过了,用邻接矩阵O(n^3)就tle了,求优化方法

Posted by scuwf at 2012-03-18 14:31:37 on Problem 3259
#include<stdio.h>
#define INF 0x7fffffff
#define MAX 501
int edge[MAX][MAX],d[MAX];
int main()
{
	int t,i,j,k,n,m,w,a,b,c,relax;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d%d%d",&n,&m,&w);
		for(i=1;i<=n;i++)
		{
			for(j=i+1;j<=n;j++) edge[i][j]=edge[j][i]=INF;
		}
		for(i=0;i<m;i++)
		{
			scanf("%d%d%d",&a,&b,&c);
			if(c<edge[a][b]) edge[a][b]=edge[b][a]=c;
		}
		for(i=0;i<w;i++)
		{
			scanf("%d%d%d",&a,&b,&c);
			if(-c<edge[a][b]) edge[a][b]=-c;
		}
		for(i=1;i<=n;i++) d[i]=0;
		relax=0;
		for(k=0;k<n;k++)
		{
			relax=0;
			for(i=1;i<=n;i++)
			{
				for(j=1;j<=n;j++)
				{
					if(edge[j][i]!=INF&&edge[j][i]+d[j]<d[i])
					{
						d[i]=edge[j][i]+d[j];
						relax=1;
					}
				}
			}
			if(!relax) break;
		}
		if(relax) printf("YES\n");
		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