• 常规并查集模板


    常规并查集

    模板

    #define Maxsize 100+1
    int f[Maxsize];
    
    void init(int n){
      for(int i = 1; i <= n; i++)
        f[i] = i;
    }
    
    int find_f(int a){
      if(f[a] == a){
        return a;
      }else{
        return f[a] = find_f(f[a]);
      }
    }
    
    void union_f(int a,int b){
      int af = find_f(a);
      int bf = find_f(b);
      f[bf] = af;
    }
    
    bool same_f(int a,int b){
      return find_f(a) == find_f(b);
    }
    

    按秩合并

    可以提高效率,减少路径压缩

    #define Maxsize 100+1
    
    int f[Maxsize];
    int r[Maxsize];
    
    void init(int n){
      for(int i = 1; i <= n; i++){
        f[i] = i;
        r[i] = 0;
      }
    }
    
    int find_f(int a){
      if(f[a] == a){
        return a;
      }else{
        return f[a] = find_f(f[a]);
      }
    }
    
    int union_f(int a,int b){
      int af = find_f(a);
      int bf = find_f(b);
      
      if(r[af] > r[bf]){
        f[bf] = af;
      }else if(r[af] < r[bf]){
        f[af] = bf;
      }else{
        f[bf] = af;
        r[af]++;
      }
    }
    
    int same_f(int a,int b){
      return find_f(a) == find_f(b);
    }
    
    ---- suffer now and live the rest of your life as a champion ----
  • 相关阅读:
    poj 2104(线段树)
    poj 1962(并查集+带权更新)
    hdu 2818(并查集,带权更新)
    hdu 1856
    hdu 3172
    hdu 1325(并查集)
    hdu 5023
    pku 2777(经典线段树染色问题)
    hdu 1671(字典树判断前缀)
    hdu 1247 (字典树入门)
  • 原文地址:https://www.cnblogs.com/popodynasty/p/13320679.html
Copyright © 2020-2023  润新知