并查集模板

发一个新学的并查集模板吧。

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int n,pre[10005],m,rank[10005];
 4 void init(int t)//初始化 
 5 {
 6     for(int i=1;i<=t;i++)
 7     {
 8         pre[i]=i;
 9         rank[i]=1;
10     }
11 }
12 int find_pre(int x)//查找根节点 
13 {
14     if(pre[x]==x) return x;
15     else return find_pre(pre[x]);
16 }
17 int compress_pre(int x)//路径压缩 
18 {
19     if(pre[x]==x)
20     {        
21         return x;      
22     }
23     return pre[x]=find_pre(pre[x]);   
24 }
25 bool same(int x,int y)//判断是否相同 
26 {
27     if(find_pre(x)==find_pre(y)) return true;
28     else return false;
29 }
30 void unite_pre(int x,int y)//合并 
31 {
32     int fx,fy;
33     fx=find_pre(x);
34     fy=find_pre(y);
35     if(fx==fy) return ;
36     else
37     {
38         if(rank[fx]>rank[fy]) pre[fy]=fx;
39         else
40         {
41             if(pre[fx]==pre[fy]) rank[fy]++;
42             pre[fx]=fy;
43         }
44     }
45 }
46 int main()
47 {
48     scanf("%d%d",&n,&m);
49     init(n);
50     for(int i=1;i<=m;i++)
51     {
52         int x,y,z;
53         scanf("%d%d%d",&x,&y,&z);
54         if(x==1) 
55         {
56             unite_pre(y,z);
57             compress_pre(y);
58         }
59         if(x==2) 
60         {
61             if(same(y,z)==true) 
62             {
63                 printf("Y\n");
64                 compress_pre(y);
65             }
66             else 
67             {
68                 printf("N\n");
69                 compress_pre(y);
70                 compress_pre(z);
71             }
72         }
73     }
74     return 0;
75 }
模板

 

转载于:https://www.cnblogs.com/jiuduSHENBENG/p/10312800.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值