hihocoder1066 并查集

并查集可实现集合的快速合并与查找操作。路径压缩后的并查集可将每次合并或者查找的操作复杂度降低到O(1).

我的代码:

 1 #include <iostream>
 2 #include <string>
 3 #include <map>
 4 
 5 using namespace std;
 6 
 7 #define MAXN 100005
 8 
 9 map<string, int> mp;
10 
11 struct unionFindSet
12 {
13     int st[MAXN];
14     void init()
15     {
16         for(int i=0; i<MAXN; ++i)   st[i] = i;
17     }
18     int findSet(int x)
19     {
20         if(x==st[x]) return x;
21         return st[x] = findSet(st[x]); //路径压缩
22     }
23     void unionSet(int x, int y)
24     {
25         int sx = findSet(x), sy = findSet(y);
26         st[sx] = sy;
27     }
28 }ufs;
29 
30 int main()
31 {
32     int cnt, n;
33     bool op;
34     string name1, name2;
35     while(cin>>n)
36     {
37         mp.clear();
38         cnt = 0;
39         ufs.init();
40         while(n--)
41         {
42             cin>>op>>name1>>name2;
43             if(mp.find(name1)==mp.end())    mp[name1] = cnt++;
44             if(mp.find(name2)==mp.end())    mp[name2] = cnt++;
45             if(op)
46             {
47                 int s1 = ufs.findSet(mp[name1]), s2 = ufs.findSet(mp[name2]);
48                 cout<<(s1==s2?"yes":"no")<<endl;
49             }
50             else
51             {
52                 ufs.unionSet(mp[name1], mp[name2]);
53             }
54         }
55     }
56     return 0;
57 }

题目链接:http://hihocoder.com/problemset/problem/1066

转载于:https://www.cnblogs.com/pczhou/p/4296624.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值