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

用kluscal算法为什么会WA呢?以下代码上ZOJ是是AC的,可是在POJ上就是WA,大牛给看下~~

Posted by qgewfg at 2009-10-08 16:19:40 on Problem 1251 and last updated at 2009-10-09 14:07:42
我用prim在poj上过了的,现在改用kluscal,为什么就wa了呢?
我已经注意到每行数据后可能会有空格的情况了。
哪位大牛给看下,感激ing~~~~

以下是我的代码:
#include<stdio.h>
#include<stdlib.h>
#define max 101
typedef struct             //定义边类型
{
	int fromvex,endvex,cost;
}edge;

edge G[77];           //G表示总的边集合
int p,relation[27];   //p表示边的总数,relation表示连通分量静态链表

int cmp(const void *a,const void *b)
{
	return ((edge *)a)->cost - ((edge*)b)->cost;
}
int KLUSCAL(int m)
{
	int i,path=0,count=0,x,y;
	
	qsort(G,p,sizeof(edge),cmp);     //按边的权值,从小到大排序
    for(i=0;i<p;i++)
	{
        x=G[i].fromvex;
		y=G[i].endvex;
		while(relation[x]!=0 ) x=relation[x];      //一直找到x所在分量的表尾,下同
        while(relation[y]!=0 ) y=relation[y];
		if(x!=y)              //如果起点和终点不在同一个连通分量中
		{   
			count++;            //边数加1
			path+=G[i].cost;    //权值累加
            relation[x]=y;      //链接两个连通分量链表
		}
		if(count==m-1) break;       //如果选出了m-1条边,则构造好了最小生成树
	}
    return path;                //返回权值总和
}

int main()
{
	int n,i,t,j,m;
	char ch1,ch2,temp;

	while(scanf("%d",&n),n)
	{
	   m=n;   p=0;
	   for(i=1;i<=m;i++)           //初始化连通分量链表
		   relation[i]=0;
	   while(temp=getchar()!='\n');     //每行数据后可能会有多余的空格
       n--;
	   while(n--)
	   {
		   ch1=getchar();
		   getchar();
           i=ch1-64;
		   scanf("%d",&t);
		   getchar();
		   while(t--)
		   {
			   ch2=getchar();
			   getchar();
			   j=ch2-64;
			   G[p].fromvex=i;
			   G[p].endvex=j;
			   scanf("%d",&G[p++].cost);
			   temp=getchar();
		   }
		   while(temp!='\n') temp=getchar();
	   }
       printf("%d\n",KLUSCAL(m));
	}
    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