并查集模板

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

 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
");
64                 compress_pre(y);
65             }
66             else 
67             {
68                 printf("N
");
69                 compress_pre(y);
70                 compress_pre(z);
71             }
72         }
73     }
74     return 0;
75 }
模板
原文地址:https://www.cnblogs.com/jiuduSHENBENG/p/10312800.html