您的位置:首页 > 其它

HDU 1213 How Many Tables 基础并查集★

2017-07-31 19:59 393 查看


题意:

n个人参加晚宴;

完全不认识的两个人不能被分配在同一餐桌;

认识具有传递性:A认识B B认识C,那么A和C也认识.


题解:

很明显的并查集模版题.

将认识两个人合并到同一集合;

最后统计有多少个不同的集合即可;

#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<string>
#include<cstring>
#include<cstdio>
const int maxn=100005;
const int INF=0x3f3f3f3f;
typedef long long LL;
using namespace std;
int par[maxn];
int N,M;
void init()
{
for(int i=0;i<=N;i++) par[i]=i;
}
int GetRoot(int a)
{
return par[a]==a?a:par[a]=GetRoot(par[a]);
}

void Merge(int a,int b)
{
int p1=GetRoot(a);
int p2=GetRoot(b);
if(p1!=p2) par[p2]=p1;
}

int main()
{
// freopen("E:\\ACM\\test.txt","r",stdin);
int T,a,b;
cin>>T;
while(T--)
{
cin>>N>>M;
init();
for(int i=0;i<M;i++)
{
cin>>a>>b;
Merge(a,b);
}
int ans=0;

for(int i=1;i<=N;i++)
if(par[i]==i) ++ans; //关键的两行

cout<<ans<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  acm-icpc HDU 并查集