标签:并查集
1 3 Fred Barney Barney Betty Betty Wilma
2 3 4这题可以用并查集+map来做,注意可能输入的两个字符串相同。#include<stdio.h> #include<string.h> #include<algorithm> #include<map> #include<string> using namespace std; int pre[100010],num[100010]; int find(int x) { int i,j=x,r=x; while(r!=pre[r])r=pre[r]; while(j!=pre[j]){ i=pre[j]; pre[j]=r; j=i; } return r; } int main() { int T,n,m,i,j,index,a,b,t1,t2,sum; char s1[30],s2[30]; while(scanf("%d",&T)!=EOF) {while(T--) { map<string,int>hash; hash.clear(); index=1; scanf("%d",&n); for(i=1;i<=100005;i++){ pre[i]=i;num[i]=1; } for(i=1;i<=n;i++){ scanf("%s%s",s1,s2); if(hash[s1]==0)hash[s1]=index++; if(hash[s2]==0)hash[s2]=index++; t1=find(hash[s1]); t2=find(hash[s2]); if(t1==t2)printf("%d\n",num[t1]); else{ pre[t1]=t2; num[t2]=num[t2]+num[t1]; printf("%d\n",num[t2]); } } } } return 0; }
标签:并查集
原文地址:http://blog.csdn.net/kirito_acmer/article/details/45603745