您的位置:首页 > 其它

hdoj 1213 How Many Tables 并查集模板

2016-08-06 17:41 363 查看

简单的并查集应用

How Many Tables

#include<iostream>
using namespace std;
int f[1001];
int findroot(int x)
{
if(x == f[x])return x;
else return findroot(f[x]);
}
void unionset(int x,int y)
{
x=findroot(x);
y=findroot(y);
f[x] = y;              //集合拼接
}
int main()
{
int t,m,n,a,b,ans;
cin>>t;
while(t--)
{
ans = 0;
cin>>m>>n;
for(int i = 1;i<=m;i++)//初始化时每个元素本身代表一个集合
f[i]=i;
for(int i=0;i<n;i++)
{
cin>>a>>b;
unionset(a,b);        //将元素合并到一个集合
}
for(int i =1;i<=m;i++)    //找尾巴的数量,一条尾“尾巴”代表含有一个集合
if(f[i]==i)
ans++;
cout<<ans<<endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: