套模板就行,最后的结果用set保存。
#include <iostream>
#include <set>
using namespace std;
#define maxn 1005
int par[maxn];
void init(int a)
{
for (int i = 1; i <= a; i++) par[i] = i;
}
int find(int x)
{
return par[x] == x ? x : par[x] = find(par[x]);
}
void unite(int a, int b)
{
if (find(a) == find(b)) return;
a = find(a);
b = find(b);
par[a] = b;
return;
}
int main(void)
{
int t;
cin >> t;
while (t--) {
int n, m;
cin >> n >> m;
init(n);
for (int i = 1; i <= m; i++) {
int a, b;
cin >> a >> b;
unite(a, b);
}
set<int> st;
for (int i = 1; i <= n; i++) st.insert(find(i));
cout << st.size() << endl;
}
return 0;
}