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 shunfeng at 2008-08-04 11:04:44 on Problem 2524
#include<stdio.h>
#include<memory>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<math.h>
using namespace std;
int father[51000],rank[51000];
int getfather(int a)
{
	int res,p,tep;
	if(a==father[a])
		res=a;
	else
	{
		p=a;
		while(p!=father[p])
		   p=father[p];
		while(a!=p)
		{
			tep=a;father[tep]=p;a=father[a];
		}
		res=p;
	}
	return res;
}
int main()
{
	int N,M,i,x,y,x1,y1,num,count=0;
	while(1)
	{
		count++;
		scanf("%d%d",&N,&M);
		if(N==0&&M==0)
			break;
		memset(father,0,sizeof(father));
		memset(rank,0,sizeof(rank));
		for(i=1;i<=N;i++)
		{
			father[i]=i;
			rank[i]=1;
		}
		num=N;
		for(i=0;i<M;i++)
		{
			scanf("%d%d",&x,&y);
			x1=getfather(x);y1=getfather(y);
			if(x1!=y1)
			{
				if(rank[x1]>rank[y1])
				{
					rank[x1]+=rank[y1];
					father[y1]=father[x1];
				}
				else
				{
					rank[y1]+=rank[x1];
					father[x1]=father[y1];
				}
				num--;
			}
		}
		printf("Case %d: %d\n",count,num);
	}
	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