1 3 Fred Barney Barney Betty Betty Wilma
2 3 4
#include<iostream> #include<map> #include<stdio.h> using namespace std; int par[100005],num[100005]; int findi(int x) { if(par[x]==x) return x; return par[x]=findi(par[x]); } void unioni(int x,int y) { int xx=findi(x); int yy=findi(y); if(xx==yy) cout<<num[xx]<<endl; else { par[xx]=yy; num[yy]=num[yy]+num[xx]; cout<<num[yy]<<endl; } } int main() { int n; while(cin>>n) { map<string,int >ren; while(n--) { ren.clear(); for(int i=1;i<=100000;i++) { par[i]=i; num[i]=1; } int m; cin>>m; string a,b; int t=1; for(int i=0;i<m;i++) { cin>>a>>b; if(ren[a]==0) ren[a]=t++; if(ren[b]==0) ren[b]=t++; int x=ren[a]; int y=ren[b]; unioni(x,y); } } } return 0; }
原文:http://www.cnblogs.com/2014slx/p/7237098.html