题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1213
题目大意:
N个朋友聚会,只有认识的人才会坐在一桌。给你M个朋友关系(A,B),表示A认识B。且认识
关系具有传递性。即如果A认识B,B认识C,那么A也认识C。所以A、B、C可以坐在一桌上。
那么问题来了:问:如果让认识的人坐一桌,那么最少要安排多少张桌子才能满足要求。
思路 :
直接能想到用并查集来做。对于所给认识关系(A、B),查找二人的父节点是否相同,不相同则并
为一个集合,相同说明之前已经认识了(不做出来)。最后统计集合的个数就行了。
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
const int MAXN = 1100;
int father[MAXN],ANS[MAXN];
int Find(int x)
{
if(x != father[x])
father[x] = Find(father[x]);
return father[x];
}
int main()
{
int T,a,b,M,N;
cin >> T;
while(T--)
{
memset(ANS,0,sizeof(ANS));
cin >> N >> M;
for(int i = 0; i <= N; ++i)
father[i] = i;
for(int i = 0; i < M; ++i)
{
cin >> a >> b;
a = Find(a);
b = Find(b);
if(a != b)
father[b] = a;
}
int ans = 0;
for(int i = 1; i <= N; ++i)
{
a = Find(i);
ANS[a]++;
}
for(int i = 1; i <= N; ++i)
if(ANS[i] != 0)
ans++;
cout << ans << endl;
}
return 0;
}原文:http://blog.csdn.net/lianai911/article/details/43613867