HDU 1213(How Many Tables)
作者:互联网
使用并查集,套用基本模板即可。
#include <iostream>
using namespace std;
const int MAXN = 1005;
int father[MAXN]; //父结点
//初始化并查集
void makeSet(int n)
{
for (int i = 1; i <= n; i++)
father[i] = i;
}
//查找x所在集合的代表元素(所在树的根结点)
int find(int x)
{
if (x != father[x])
father[x] = find(father[x]);
return father[x];
}
//合并x所在集合和y所在集合
void unionSet(int x, int y)
{
int fx = find(x);
int fy = find(y);
if (fx != fy)
father[fx] = fy;
}
int main()
{
int T;
cin >> T;
while (T--)
{
int N, M;
cin >> N >> M;
makeSet(N);
int A, B;
for (int i = 0; i < M; i++)
{
cin >> A >> B;
unionSet(A, B);
}
int ans = 0; //桌子数量
for (int i = 1; i <= N; i++)
{
if (i == father[i])
++ans;
}
cout << ans << endl;
}
return 0;
}
继续加油。
标签:Tables,HDU,1213,int,查集,cin,MAXN,makeSet 来源: https://blog.csdn.net/Intelligence1028/article/details/104637652