并查集(Union-Find)

Date:2019-06-23 13:42:53

 1 //定义
 2 int father[N];  //father[1]=2,即2是1的父亲,根结点用father[i]=i表示
 3 
 4 //初始化
 5 for(int i=1; i<=N; i++)
 6     father[i]=i;    //初始时有N个独立的集合
 7 
 8 //查找
 9 //对于给定的结点,寻找其根结点
10 int Find(int x)
11 {
12     if(father[x] == x)
13         return x;
14     Find(father[x]);
15 }
16 
17 //合并
18 void Union(int a, int b)
19 {
20     int fa = Find(a);
21     int fb = Find(b);
22     father[fb] = fa;    //不能用father[a]=b
23     Find2(b);          //将fb中的结点更新至fa
24 }
25 
26 
27 //路径压缩
28 //把当前查询结点的路径上所有的结点的父亲都指向根结点
29 int Find2(int x)
30 {
31     int r = x;
32     while(x != father[x])
33         x = father[x];
34     //此处x已经是根结点
35     while(r != father[r])
36     {
37         int z = r;
38         r = father[r];
39         father[z] = x;
40     }
41 }
42 
43 //递归写法
44 int Find2(int x)
45 {
46     if(x == father[x])
47         return x;
48     fathre[x] = Find2(father[x]);
49 }

 

转载于:https://www.cnblogs.com/blue-lin/p/11072511.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值