poj 2524

并查集水题

#include <iostream>
using namespace std;
const int maxn=50010;
int tot,m,n;
struct node
{
	int rank;
	int data;
	int parent;
}t[maxn];
void init()
{
	for(int i=1;i<=n;i++)
	{
		t[i].data=i;
		t[i].rank=1;
		t[i].parent=i;
	}
}
int find(int p)
{
	if(p!=t[p].parent)
		t[p].parent=find(t[p].parent);//路径压缩
	return t[p].parent;//易错点
}
void Union(int x,int y)
{
	int xp=find(x);
	int yp=find(y);
	if(xp!=yp)
	{
		if(t[xp].rank<t[yp].rank)//按秩的大小合并,和上面的路径压缩的作用一样都是提高了查找速度
			t[xp].parent=yp;
		else
		{
			t[yp].parent=xp;
			if(t[xp].rank==t[yp].rank)
				t[xp].rank++;
		}
		tot--;
	}
}
int main()
{
	int x,y,amount=0;
	while(cin>>n>>m&&!(n==0&&m==0))
	{
		init();
		amount++;
		tot=n;
		for(int i=0;i<m;i++)
		{
			cin>>x>>y;
			Union(x,y);
		}
		cout<<"Case "<<amount<<": "<<tot<<endl;
	}
	return 0;
}


 

 

 

posted @ 2012-10-15 09:12  LJ_COME!!!!!  阅读(83)  评论(0编辑  收藏  举报