ZOJ——2833
并查集的寻根和合并操作
#include <iostream>
using namespace std;
int friends[100005];
//寻找根节点
int find(int x)
{
while(friends[x]>0)
x=friends[x];
return x;
}
//合并两节点
void Union(int x, int y)
{
int r1=find(x);
int r2=find(y);
//根不相同
if(r1!=r2)
{
//两根相加,记录节点总数,实则为负数
int temp = friends[r1]+friends[r2];
//哪个节点数更大哪个做根
if(friends[r1]>friends[r2])
{
friends[r1]=r2;
friends[r2]=temp;
}
else
{
friends[r2]=r1;
friends[r1]=temp;
}
}
}
int main()
{
int n, m;
int count=0;
while (cin>>n>>m)
{
if(count!=0)
cout<<endl;
count++;
cout<<"Case "<<count<<":"<<endl;
//初始化 所有朋友都是根
for(int i=1; i<=n; i++)
friends[i]=-1;
//赋值
while(m--)
{
char s[2];
cin>>s;
//输入字符为m是并集
if(s[0]=='M')
{
int a, b;
cin>>a>>b;
Union(a, b);
}
else
{
int x;
cin>>x;
cout<<-friends[find(x)]<<endl;
}
}
}
system("pause");
return 0;
}