***并查集模板题
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<queue> #include<algorithm> using namespace std; typedef long long LL; #define N 1010 #define INF 0x3f3f3f3f int father[N]; int Find(int x) { while(x!=father[x]) x=father[x]; return x; } int main() { int T, n, m, a, b, x, y, p, ans, k; scanf("%d", &T); while(T--) { scanf("%d%d", &n, &m); for(int i = 0; i <= n; i++) father[i] = i; for(int i = 1; i <= m; i++) { scanf("%d%d", &a, &b); x = Find(a); y = Find(b); if(x != y) father[x] = y; } p = Find(1); ans = 1; for(int i = 1; i <= n; i++) { k = Find(i); if(k != p) { ans++; father[k] = p; } } printf("%d ", ans); } return 0; }