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

压缩超时,不压AC...什么问题,谁帮优化下...谢谢

Posted by yongyao_li at 2009-04-22 00:56:52 on Problem 2524
#include<iostream>
using namespace std;
#define MAXN 50000

int parent[MAXN+1];

void init(int n)
{
	int i;
	for(i=1;i<=n;i++)
		parent[i]=-1;
}


int find(int x)
{
	/*不知道是不是我的压缩有问题
	int tmp,
		p=x;
	while(parent[p]>0)
		p=parent[x];      //p==root
	while(x!=p)
	{
		tmp=parent[x];
		parent[x]=p;
		x=tmp;
	}
	return p;
	*/下面是不压缩的
	if(parent[x]<0)
		return x;
	else return find(parent[x]);
}

void Union(int x,int y)
{
	int root1=find(x),
		root2=find(y);
	if(root1==root2) return;
	if(parent[root1]<parent[root2])
	{
		parent[root1]+=parent[root2];
		parent[root2]=root1;
	}else{
		parent[root2]+=parent[root1];
		parent[root1]=root2;
	}
}


int main()
{
	int n,m,x,y,i,k=1,sum;
	memset(parent,-1,sizeof(parent));
	while( scanf("%d%d",&n,&m)==2 && n!=0 )
	{
		//init(n);
		sum=0;
		while(m--)
		{
			scanf("%d%d",&x,&y);
			Union(x,y);
		}
		for(i=1;i<=n;i++)
		{
			if(parent[i]<0)
				sum++;
			parent[i]=-1;
		}
		printf("Case %d: %d\n",k++,sum);
	}
}

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