hdu Disjoint-set problems
Disjoint-set namely Union-Find set!
hdu 3172 virtual friends http://acm.hdu.edu.cn/showproblem.php?pid=3172
Yes! A very interesting problem!
Whenever a friendship is formed,printf the number of the peoplein the social network.
OK, I failed lots of time. And all are "Time Limit Exceeded".
But to my surprise! I just replace the "cin" with “scanf” ,"cout" with "printf" in the code,and accepted!
learned: scanf/printf is more efficient than cin/cout;
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<iostream> 2 #include<cstring> 3 #include<string> 4 #include<map> 5 #include<cstdio> 6 using namespace std; 7 int f[200005],num[200005]; 8 void sequence() 9 { 10 int i; 11 for(i=1;i<200005;i++) 12 { 13 f[i]=i; 14 num[i]=1; 15 } 16 } 17 int find(int x) 18 { 19 if(x!=f[x]) 20 f[x]=find(f[x]); 21 return f[x]; 22 23 } 24 void Union(int x,int y) 25 { 26 x=find(x); 27 y=find(y); 28 if(x==y) 29 { 30 printf("%d\n",num[x]); 31 } 32 else 33 { 34 f[y]=x; 35 num[x]+=num[y]; 36 printf("%d\n",num[x]); 37 } 38 } 39 int main() 40 { 41 int t; 42 map<string,int>match; 43 while(scanf("%d",&t)!=EOF) 44 { 45 int k; 46 string name1,name2; 47 while(t--) 48 { 49 sequence(); 50 match.clear(); 51 scanf("%d",&k); 52 int s=1; 53 while(k--) 54 { 55 cin>>name1>>name2; 56 if(match.find(name1)==match.end()) 57 { 58 s++;match[name1]=s; 59 } 60 if(match.find(name2)==match.end()) 61 { 62 s++;match[name2]=s; 63 } 64 Union(match[name1],match[name2]); 65 } 66 } 67 } 68 return 0; 69 } 70 71 72 73 74
Post by heat_nan @2013-03-17 12:03