标签:des style blog http io ar color os sp
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5491 Accepted Submission(s): 1519
题意: 逐步给你一些关系网,对于每一步求所给出的两个人合并之后所构成的关系网。
代码:
1 #include<cstdio> 2 #include<cstring> 3 #include<cstdlib> 4 #include<iostream> 5 #include<map> 6 #include<string> 7 using namespace std; 8 const int maxn=100003; 9 int father[maxn]; 10 int rank[maxn]; 11 //初始化 12 void init( int n) 13 { 14 for(int i =0;i<=n ;i++){ 15 father[i]=i; 16 rank[i]=1; 17 } 18 } 19 //搜索 20 int fin(int x) 21 { 22 int tem=x; 23 while(x!=father[x]){ 24 x=father[x]; 25 } 26 //进一步压缩 27 while(tem!=father[tem]) 28 { 29 tem=father[tem]; 30 father[tem]=x; 31 } 32 33 return x; 34 } 35 void Union(int a,int b){ 36 a=fin(a); 37 b=fin(b); 38 if(a!=b){ 39 if(rank[a]<rank[b]){ 40 rank[b]+=rank[a]; 41 father[a]=b; 42 } 43 else{ 44 rank[a]+=rank[b]; 45 father[b]=a; 46 } 47 } 48 } 49 map<string,int>sac; 50 char aa[maxn][21],bb[maxn][21]; 51 52 int main() 53 { 54 int t,n; 55 while(scanf("%d",&t)!=EOF) 56 { 57 while(t--){ 58 scanf("%d",&n); 59 if(!sac.empty()) sac.clear(); 60 int cnt=0; 61 for(int i=0;i<n ;i++){ 62 scanf("%s%s",aa[i],bb[i]); 63 // map<string,int>::iterator it; 64 //it=sac.find(aa[i]); 65 if(sac.find(aa[i])==sac.end()) 66 sac[aa[i]]=++cnt; 67 68 // it=sac.find(bb[i]); 69 if(sac.find(bb[i])==sac.end()) 70 { 71 // posb=sac.size(); 72 // sac.insert(pair<string,int>(bb,posb)); 73 sac[bb[i]]=++cnt; 74 } 75 } 76 init(cnt); 77 for(int i=0;i<n;i++) 78 { 79 Union(sac[aa[i]],sac[bb[i]]); 80 printf("%d\n",rank[fin(sac[aa[i]])]); 81 } 82 } 83 } 84 return 0; 85 }
hdu 3172 Virtual Friends (映射并查集)
标签:des style blog http io ar color os sp
原文地址:http://www.cnblogs.com/gongxijun/p/4147855.html