题目链接点击打开链接
附上代码:
#include<iostream>
using namespace std;
int tr[1010];
int find(int x)//寻找树根
{
int r = x;
while (r != tr[r])
{
r = tr[r];
}
return r;
}
using namespace std;
int tr[1010];
int find(int x)//寻找树根
{
int r = x;
while (r != tr[r])
{
r = tr[r];
}
return r;
}
int main()
{
int t;
cin >> t;
while (t--)
{
int m, n,x,y;
cin >> m >> n;
for (int i = 1; i <= m; i++)tr[i] = i;
for (int i = 0; i < n; i++)
{
cin >> x >> y;
int fx, fy;
fx = find(x);
fy = find(y);
if (fx != fy){ tr[fx] = fy; }
}
int count = 0;
for (int i = 1; i <= m; i++)
{
if (tr[i] == i)count++;
}
cout << count << endl;
cin.get();
cin.get();
}
}
{
int t;
cin >> t;
while (t--)
{
int m, n,x,y;
cin >> m >> n;
for (int i = 1; i <= m; i++)tr[i] = i;
for (int i = 0; i < n; i++)
{
cin >> x >> y;
int fx, fy;
fx = find(x);
fy = find(y);
if (fx != fy){ tr[fx] = fy; }
}
int count = 0;
for (int i = 1; i <= m; i++)
{
if (tr[i] == i)count++;
}
cout << count << endl;
cin.get();
cin.get();
}
}