HDU 1213 How Many Tables(并查集模板)

时间:2023-03-09 02:19:09
HDU 1213 How Many Tables(并查集模板)

http://acm.hdu.edu.cn/showproblem.php?pid=1213

题意:

这个问题的一个重要规则是,如果我告诉你A知道B,B知道C,这意味着A,B,C知道对方,所以他们可以留在一个桌子。

例如:如果我告诉你A知道B,B知道C,D知道E,所以A,B,C可以留在一个桌子中,D,E必须留在另一个桌子中。所以Ignatius至少需要2个桌子。

思路:

并查集模板题。

#include<iostream>
using namespace std; int p[]; int find(int x)
{
return p[x] == x ? x : find(p[x]);
} void Unions(int x, int y)
{
p[x] = y;
} int main()
{
//freopen("D:\\txt.txt", "r", stdin);
int T, a, b, n, m;
cin >> T;
while (T--)
{
cin >> n >> m;
for (int i = ; i <= n; i++)
p[i] = i;
for (int i = ; i < m; i++)
{
cin >> a >> b;
int x = find(a);
int y = find(b);
if (x != y)
Unions(x, y);
}
int ans = ;
for (int i = ; i <= n;i++)
if (p[i] == i) ans++;
cout << ans << endl;
}
return ;
}