hdu 2473 Junk-Mail Filter 并查集
#include <stdio.h> #include <string.h> #define maxn 1001000 int id[maxn],p[maxn]; bool vis[maxn]; int find(int x) { if(p[x]==x) return x; else return p[x]=find(p[x]); } void link(int a,int b) { int x=find(a); int y=find(b); if(x!=y) p[x]=y; } int main() { int n,m; int x,y; int sum=0; int cnt,i; while(1) { scanf("%d%d",&n,&m); cnt=n; char c; sum++; if(n==0&&m==0) break; for(i=0;i<maxn;i++) p[i]=id[i]=i; for(i=1;i<=m;i++) { getchar(); scanf("%c",&c); if(c=='M') { scanf("%d%d",&x,&y); link(id[x],id[y]); } else { scanf("%d",&x); id[x]=cnt++; } } int ans=0; memset(vis,0,sizeof(vis)); for(i=0;i<n;i++) { x=find(id[i]); if(vis[x]==0) { vis[x]=1; ans++; } } printf("Case #%d: %d\n",sum,ans); } }