板子题不多说,上代码
#include<iostream> #include<cstdio> #include<cstring> using namespace std; int F[1005]; int find(int x){ if(F[x]==-1) return x; return F[x]=find(F[x]); } void bing(int a,int b){ int t1=find(a); int t2=find(b); if(t1!=t2) F[t1]=t2; } int main(){ int T,n,m,a,b; cin >> T; while(T--){ scanf("%d%d",&n,&m); for(int i=0;i<=n;i++) F[i]=-1; while(m--){ scanf("%d%d",&a,&b); bing(a,b); } int ans=0; for(int i=1;i<=n;i++) if(F[i]==-1) ans++; printf("%d ",ans); } }