• dd第一课:并查集


     1 #include <stdio.h>
     2 #include <string.h>
     3 #define MAX 1000
     4 
     5 int p[MAX];
     6 int rank[MAX];
     7 void init(int n){
     8     int i;
     9 //    memset(rank, 0, sizeof(rank));
    10     for(i=1;i<n;i++) {p[i]=i;rank[i]=0;}
    11 }
    12 
    13 
    14 int find_root_digui(int x){
    15     if(x!=p[x])
    16         return p[x]=find_root(p[x]);
    17     else return x;
    18 } 
    19 
    20 int find_root(int x){
    21     
    22     int i=x;
    23     while(i!=p[i])
    24         i=p[i];
    25     int rot=i;
    26     int temp;
    27     i=x;
    28     while (i!=p[i]){
    29         temp=i;
    30         i=p[i];
    31         p[temp]=rot;
    32     }
    33     return rot;
    34 }
    35 
    36 int conn(int x,int y){
    37     x=find_root(x);
    38     y=find_root(y);
    39     return x==y;
    40 }
    41 
    42 void _union(int x,int y){
    43     x=find_root(x);
    44     y=find_root(y);
    45 
    46     if(rank[x]>=rank[y])
    47         p[y]=x;
    48     else p[x]=y;
    49     
    50     if(rank[x]==rank[y]) rank[x]++;
    51 }
    52     
    53 void try() 
    54 {
    55     _union(1,2);
    56     _union(3,4);
    57     _union(2,4);
    58     _union(5,6);
    59     _union(7,8);
    60     _union(6,8);
    61     _union(2,6);
    62     int root = find_root(8);
    63     printf("root = %d\n", root);
    64     
    65     for(int i=1; i<10; i++)
    66     {
    67         printf("p[%d]=%d, rank[%d]=%d\n", i, p[i], i, rank[i]);
    68     }
    69     
    70     while(1)
    71     {
    72         int a, b;
    73         scanf("%d%d", &a, &b);
    74         printf("%d\n", conn(a,b));
    75         printf("%d\n",rank[1]);
    76         printf("%d\n",find_root(1));
    77     }
    78     
    79 }
    80 
    81 int main(){
    82     int n=20;
    83     init(n);
    84     try();
    85     return 0;
    86 }
  • 相关阅读:
    os
    虚拟站点配置
    21. Merge Two Sorted Lists
    38. Count and Say
    算法分类的书写模板
    Vue
    问题集、知识点
    [Linux] Linux命令
    回调函数在小程序中的实际应用
    小程序app.onLaunch中获取用户信息,index.onLoad初次载入时取不到值的问题
  • 原文地址:https://www.cnblogs.com/firstrate/p/3054190.html
Copyright © 2020-2023  润新知