zoukankan      html  css  js  c++  java
  • 并查集

    代码1:

    #include <bits/stdc++.h>
    using namespace std;
    
    const int maxn = 1e5 + 10;
    int par[maxn];
    int rank[maxn];
    
    void init(int n) {
        for(int i = 0; i < n; i ++) {
            par[i] = i;
            rank[i] = 0;
        }
    }
    
    int find(int x) {
        if(par[x] == x)
            return x;
        else
            return par[x] = find(par[x]);
    }
    
    int unite(int x, int y) {
        x = find(x);
        y = find(y);
        if(x == y) return;
    
        if(rank[x] < rank[y])
            par[x] = y;
        else {
            par[y] = x;
            if(rank[x] == rank[y])
                rank[x] ++;
        }
    }
    
    bool same(int x, int y) {
        return find(x) == find(y);
    }
    

      

    代码2:

    #include <bits/stdc++.h>
    using namespace std;
    
    int N;
    int c;
    int fa[20];
    
    int dfs(int z) {
        if(fa[z] == z) return z;
        else
            return fa[z] = dfs(fa[z]);
    }
    
    int main() {
        scanf("%d", &N);
        for(int i = 1; i <= N; i ++)
            fa[i] = i;
        while(N --) {
            int x, y;
            scanf("%d", &c);
            scanf("%d%d", &x, &y);
            if(c == 0)
                fa[y] = dfs(x);
            else if(c == 1) {
                if(dfs(x) == dfs(y))
                    printf("YES
    ");
                else
                    printf("NO
    ");
            }
        }
        return 0;
    }

    代码3:

    #include <bits/stdc++.h>
    using namespace std;
    
    const int maxn = 1e5 + 10;
    int f[maxn];
    int n;
    
    int Find(int x) {
      if(x != f[x]) f[x] = Find(f[x]);
      return f[x];
    }
    
    void init() {
      for(int i = 1; i <= n; i ++) {
        f[i] = i;
      }
    }
    
    int Merge(int x, int y) {
      int fx = Find(x);
      int fy = Find(y);
      if(fx != fy) {
        f[fx] = fy;
      }
    }
    
    int main() {
    
      return 0;
    }
    

      

  • 相关阅读:
    linux之iptable案例
    nginx常用命令参数
    laravel中的多对多关系详解
    MySql计算时间差函数
    总结下Mysql分表分库的策略及应用
    swoole扩展实现真正的数据库连接池
    linux常用命令整理
    innodb mvcc实现机制
    mysqlslap 压力测试使用总结
    mysql索引总结
  • 原文地址:https://www.cnblogs.com/zlrrrr/p/9649095.html
Copyright © 2011-2022 走看看