Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 8229 Accepted Submission(s): 2363
#include<iostream> #include<cstdio> #include<map> #include<string> using namespace std; #define N 200005 map<string,int>m; int father[N],dist[N]; int Find(int x) { if(father[x]!=x) father[x]=Find(father[x]); return father[x]; } void Merge(int a,int b) { int fa=Find(a); int fb=Find(b); if(fa!=fb) { father[fa]=fb; dist[fb]+=dist[fa]; } printf("%d\n",dist[fb]); } int main() { int t; while(scanf("%d",&t)!=EOF) { while(t--) { m.clear(); int n,cnt=1; string name1,name2; scanf("%d",&n); for(int i=1; i<=2*n; i++) { father[i]=i; dist[i]=1; } while(n--) { cin>>name1>>name2; if(m.find(name1)==m.end()) m[name1]=cnt++; if(m.find(name2)==m.end()) m[name2]=cnt++; Merge(m[name1],m[name2]); } } } return 0; }
原文:http://www.cnblogs.com/jasonlixuetao/p/6115125.html