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;

View Code
 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

 

转载于:https://www.cnblogs.com/heat-man/archive/2013/03/17/2964329.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值