zoukankan      html  css  js  c++  java
  • 【数据结构】并查集

    并查集

    验证链接:https://www.luogu.com.cn/problem/P3367

    同时使用按秩合并和路径压缩的写法,由于使用了按秩合并,所以路径压缩使用递归并不会爆栈。

    struct DisjointSet {
    
        static const int MAXN = 200000 + 10;
        int fnd[MAXN], siz[MAXN];
    
        void Init(int n) {
            for(int i = 1; i <= n; i++)
                fnd[i] = i, siz[i] = 1;
        }
    
        int Find(int x) {
            return (fnd[x] == x) ? x : fnd[x] = Find(fnd[x]);
        }
    
        int Size(int x) {
            x = Find(x);
            return siz[x];
        }
    
        int Merge(int x, int y) {
            x = Find(x), y = Find(y);
            if(x == y)
                return 0;
            if(siz[x] < siz[y])
                swap(x, y);
            fnd[y] = x;
            siz[x] += siz[y];
            return x;
        }
    
    } ds;
    

    并查集维护可删除链表

    struct DisjointSet {
    
        static const int MAXN = 200000 + 10;
        int prev[MAXN], next[MAXN];
    
        void Init(int n) {
            for(int i = 0; i <= n + 1; ++i)
                prev[i] = i, next[i] = i;
        }
    
        int Prev(int x) {
            return (prev[x] == x) ? x : prev[x] = Prev(prev[x]);
        }
    
        int Next(int x) {
            return (next[x] == x) ? x : next[x] = Next(next[x]);
        }
    
        void Delete(int x) {
            prev[x] = Prev(x - 1), next[x] = Next(x + 1);
        }
    
    } ds;
    
  • 相关阅读:
    poj 1634
    poj 2153
    POJ 1693
    poj 1789
    POJ 2676
    vue 路由
    用 node.js 创建第一个Hello World
    js原生Ajax 的封装和原理
    BFC原理
    怎么理解js的面向对象编程
  • 原文地址:https://www.cnblogs.com/purinliang/p/14044629.html
Copyright © 2011-2022 走看看