您的位置:首页 > 其它

poj1611 并查集

2014-11-09 00:24 155 查看
如题:http://poj.org/problem?id=1611





基础的并查集



#include<iostream>

using namespace std;

#define N 30005

#define M 505

struct Set

{

int data;

int rank;

int father;

}set
;

int findSet(int x)

{

if(set[x].father==x)

return x;

else

return findSet(set[x].father);

}

void Union(int a,int b) //a所在的集合和b所在的集合合并

{

int fa,fb;

fa=findSet(a);

fb=findSet(b);

if(fa==fb)

return;

if(set[fa].rank>set[fb].rank) //将深度小的集合放在深度大的下面

{

set[fb].father=fa;

if(set[fb].rank+1>set[fa].rank)

set[fa].rank=set[fb].rank+1;

}

else

{

set[fa].father=fb;

if(set[fa].rank+1>set[fb].rank)

set[fb].rank=set[fa].rank+1;

}

}

int main()

{

int N1,M1;

int i,j;

while(cin>>N1>>M1)

{

if(N1==0) break;

for(i=0;i<N;i++)

{

set[i].data=0;

set[i].father=i;

set[i].rank=0;

}

int n;int t1;

for(j=1;j<=M1;j++)

{

//scanf("%d",&n);

//getchar();

cin>>n;

if(n>=1)

{

// scanf("%d",&t1);

// getchar();

cin>>t1;

}

for(i=1;i<n;i++)

{

int t2;

scanf("%d",&t2);

getchar();

Union(t1,t2);

}

}

int sum=1;

for(i=1;i<N;i++)

{

if(findSet(i)==findSet(0))

sum++;

}

cout<<sum<<endl;

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: