晓轩

博客园 首页 联系 订阅 管理

#include<iostream>
#include<cstring>
using namespace std;

const int MAX=30001;

int father[MAX],rank[MAX],num[MAX];//num[MAX]用来维护集合元素个数

void Init(int n)
{
 for(int i=0;i<=n;i++)
 {
  father[i]=i;
  rank[i]=0;
  num[i]=1;
 }
}

int find(int x)
{
 while(x!=father[x])
  x=father[x];
 return x;
}

void merge(int x,int y)
{
 int fx,fy;
 fx=find(x);
 fy=find(y);
 if(fx==fy)
  return;
 if(rank[fx]<rank[fy])
 {
  father[fx]=fy;
  num[fy]+=num[fx];
 }
 else
 {
  father[fy]=fx;
  num[fx]+=num[fy];
  if(rank[fx]==rank[fy])
   rank[fx]++;
 }
}

posted on 2013-08-17 18:12  晓轩  阅读(297)  评论(0)    收藏  举报