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

    并查集的基本操作有三个:

    1. makeSet(s):建立一个新的并查集,其中包含 s 个单元素集合。
    2. unionSet(x, y):把元素 x 和元素 y 所在的集合合并,要求 x 和 y 所在的集合不相交,如果相交则不合并。
    3. find(x):找到元素 x 所在的集合的代表,该操作也可以用于判断两个元素是否位于同一个集合,只要将它们各自的代表比较一下就可以了

    1.

    const int MAXSIZE = 500;
    int uset[MAXSIZE];
     
    void makeSet(int size) {
        for(int i = 0;i < size;i++) uset[i] = i;
    }
    2.
      2.1
        
    int find(int x) {
        if (x != uset[x]) uset[x] = find(uset[x]);
        return uset[x];
    }
     
      2.2
    int find(int x) {
        int p = x, t;
        while (uset[p] != p) p = uset[p];
        while (x != p) { t = uset[x]; uset[x] = p; x = t; }
        return x;
    }
     
    3.
    void unionSet(int x, int y) {
        if ((x = find(x)) == (y = find(y))) return;
        if (rank[x] > rank[y]) uset[y] = x;
        else {
            uset[x] = y;
            if (rank[x] == rank[y]) rank[y]++;
        }
    }
     
     
     
  • 相关阅读:
    [比赛|考试]9.21上午考试
    给花_Q
    [比赛|考试] 9.17下午考试
    [比赛|考试]nowcoder NOIP提高组组第二场
    图论
    生成函数
    P4197 Peaks
    3942: [Usaco2015 Feb]Censoring
    P2245 星际导航
    P3565 [POI2014]HOT-Hotels
  • 原文地址:https://www.cnblogs.com/ouyang_wsgwz/p/6550674.html
Copyright © 2011-2022 走看看