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;
    }
  • 相关阅读:
    js在微信、微博、QQ、Safari唤起App的解决方案
    js根据ip自动获取地址(省市区)
    css行内省略号、垂直居中
    PAT1006
    PAT1005
    PAT1004
    PAT1003
    PAT1002
    PAT1001
    latex中的空格
  • 原文地址:https://www.cnblogs.com/wangdongkai/p/5376634.html
Copyright © 2011-2022 走看看