简单并查集
#include<map> #include<set> #include<queue> #include<cmath> #include<vector> #include<cstdio> #include<string> #include<cstring> #include<cstdlib> #include<iostream> #include<algorithm> #define inf 0x0f0f0f0f using namespace std; const double pi=acos(-1.0); const double eps=1e-8; typedef pair<int,int>pii; const int maxn=1000+10; int p[maxn]; bool vis[maxn]; int find(int x){return (x==p[x]?x:p[x]=find(p[x]));} int main() { //freopen("in.txt","r",stdin); int t,n,m,x,y; scanf("%d", &t); while (t--) { scanf("%d%d",&n,&m); for (int i=0;i<=n;i++) p[i]=i; for (int i=0;i<m;i++) { scanf("%d%d",&x,&y); x=find(x); y=find(y); p[x]=y; } for (int i=1;i<=n;i++) p[i]=find(i); memset(vis,0,sizeof(vis)); int ans=0; for(int i=1;i<=n;i++) if (!vis[p[i]]) { ans++; vis[p[i]]=true; } printf("%d ",ans); } //fclose(stdin); return 0; }