题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1213
题目分类:并查集
代码:
#include<stdio.h> #include<iostream> #include<algorithm> using namespace std; struct ST { int a; int b; }st[1005]; int cmp(ST x, ST y) { if(x.a==y.a) return x.b < y.b; return x.a < y.a; } int Father[1005]; int Find(int x) { if(x==Father[x]) return x; return Find(Father[x]); } int main() { int t; cin>>t; while(t--) { int n, m; cin>>n>>m; for(int i=1;i<=n;i++) Father[i] = i; for(int i=1;i<=m;i++) { cin>>st[i].a>>st[i].b; int Fa = Find(st[i].a); int Fb = Find(st[i].b); if(Fa!=Fb) Father[Fb] = Fa; } int ans = 0; for(int i=1;i<=n;i++) if(Father[i]==i) ans++; cout<<ans<<endl; } return 0; }