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

    今天效率还不错,学了许多东西,其中就有并查集,当然我只学了一小部分,还需要多做题来巩固与练习。

    #include <iostream>
    using namespace std;
    
    class DisjointSet {
    private:
        int *father, *rank;
    public:
        DisjointSet(int size) {
            father = new int[size];
            rank = new int[size];
            for (int i = 0; i < size; ++i) {
                father[i] = i;
                rank[i] = 0;
            }
        }
        ~DisjointSet() {
            delete[] father;
            delete[] rank;
        }
        //查找根结点
        int find_set(int node) {
            if (father[node] != node) {
                father[node] = find_set(father[node]); //路径压缩优化
            }
            return father[node];
        }
        //合并根结点
        bool merge(int node1, int node2) {
            int ancestor1 = find_set(node1);
            int ancestor2 = find_set(node2);
            if (ancestor1 != ancestor2) {
                if (rank[ancestor1] > rank[ancestor2]) {
                    swap(ancestor1, ancestor2);
                }
                father[ancestor1] = ancestor2;
                rank[ancestor2] = max(rank[ancestor1] + 1, rank[ancestor2]); //按秩合并优化
                return true;
            }
            return false;
        }
    };
    
    int main() {
        DisjointSet dsu(100);
        int m, x, y;
        cin >> m;
        for (int i = 0; i < m; ++i) {
            cin >> x >> y;
            bool ans = dsu.merge(x, y);
            if (ans) {
                cout << "success" << endl;
            } else {
                cout << "failed" << endl;
            }
        }
        return 0;
    }
  • 相关阅读:
    通过 Ansible role 安装 Jenkins Server
    常见 Bash 内置变量介绍
    Ansible 简介
    为容器化的 Go 程序搭建 CI
    Bash Shebang 小结
    Docker Compose 引用环境变量
    Docker Compose 之进阶篇
    Docker Compose 原理
    WEB程序调用客户端程序
    读书笔记2014第5本:《乔纳森传》
  • 原文地址:https://www.cnblogs.com/wangdongkai/p/5376634.html
Copyright © 2011-2022 走看看