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 mmx21 at 2011-03-03 10:48:28 on Problem 2524
#include <iostream>
const int MAX = 50001;
int p[MAX],rank[MAX];
int result;

int findSet(int x)
{
	if(x!=p[x])
		p[x] = findSet(p[x]);
	return p[x];
}

void Union(int x, int y)
{
	if(x == y)
		return;
	result--;
	if(rank[x] > rank[y])
	{
		p[y] = x;
	}
	else
	{
		p[x] = y;
		if(rank[x] == rank[y])
			rank[y]++;
	}
}

int main()
{
	int i,j;
	int s1,s2;
	int x,y;
	int n,m;
	int t = 1;
	while(true)
	{
		scanf("%d %d",&n,&m);
		if(n==0&&m==0) break;
		result = n;
		for(i = 1; i <= n; i++)
		{
			p[i] = i;
			rank[i] = 0;
		}
		for(i = 1; i <= m; i++)
		{
			scanf("%d %d",&x,&y);
			s1 = findSet(x);
			s2 = findSet(y);
			Union(s1,s2);
		}
		printf("Case %d: ",t++);
		printf("%d\n",result);
	}
	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