zoj 2048 / poj 1751 Highways prim算法 (无限wa注意)

题目链接 :http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1048

 

解题报告:在zoj上wa了多次还是过不了,感觉很郁闷,就去poj上提交,结果poj可以过。

代码其实很快就敲出来了,只是一直wa改了很久也没有发现错误,刚开始我还以为是已经完全联通的城市需要输出一个空行呢,结果只是两组数据之间夹一个空行,zoj上顺利通过,希望wa的可以借鉴一下。

 

代码:

#include<cstdio>
#include<cstring>
#include<cmath>
#define maxn 800
#define INF 0x7fffffff

using namespace std;

struct node
{
	int x, y;
}vex[maxn];

int edge[maxn][maxn];
int nearvex[maxn];
int lowcost[maxn];
int n, m;

void Prim( int u0 )
{
	int i, j, flag = 0;
	for( i = 1; i <= n; i++ )
	{
		lowcost[i] = edge[u0][i];
		nearvex[i] = u0;
	}
	nearvex[u0] = -1;
	for( i = 1; i < n; i++ )
	{
		int min = INF;
		int v = -1;
		for( j = 1; j <= n; j++ )
		{
			if(nearvex[j] != -1 && lowcost[j] < min )
			{
				min = lowcost[j] ;
				v = j;
			}
		}
		if( v != -1)
		{
			if(min == 0)
			{
				nearvex[v] = -1; 
			}
			else
			{
				printf("%d %d\n",nearvex[v],v);
				flag = 1;
				nearvex[v] = -1;
			}
		}
		for( j = 1; j <= n; j++ )
		{
			if( nearvex[j] != -1 && edge[v][j] < lowcost[j] )
			{
				lowcost[j] = edge[v][j];
				nearvex[j] = v;
			}
		}
	}
//	if(!flag) printf("\n");
//	else printf("\n\n");
}

int main( )
{
	int T, i, j, u, v;
	scanf("%d", &T);
	while( T-- )
	{
		memset(edge, 0, sizeof(edge));
		memset(nearvex, 0, sizeof(nearvex));
		memset(lowcost, 0, sizeof(lowcost));
		scanf( "%d", &n );
		for( i = 1; i <= n; i++ )
			scanf("%d %d", &vex[i].x, &vex[i].y);
		for( i = 1; i <= n; i++ )
		{
			for( j = 1; j <= n; j++ )
			{
				if(i == j ) edge[i][j] = INF;
				else if(i < j)	edge[i][j] = edge[j][i] = (vex[i].x-vex[j].x)*(vex[i].x-vex[j].x)+(vex[i].y-vex[j].y)*(vex[i].y-vex[j].y);
			}
		}
		scanf("%d",&m);
		for( j = 0; j < m; j++ )
		{
			scanf("%d%d", &u, &v);
			edge[u][v] = edge[v][u] = 0;
		}	
		Prim( 1 );
		if(T) printf("\n"); 
	} 
	return 0;
}

 

你可能感兴趣的:(Prim算法,zoj 2048,poj1751,无限wa)