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;
    }
  • 相关阅读:
    ADC测试matlab代码
    matlab的滤波器仿真——低通滤波器与插值滤波器
    PDF转Image最终方案
    多线程和蕃茄炒蛋
    git学习总结
    踩坑了,当前目录问题
    Angular 1.x 升级到 Angular 2
    打造AngularJs2.0开发环境
    发布一个自用的ansi转utf8程序
    用itextsharp打印pdf示例
  • 原文地址:https://www.cnblogs.com/wangdongkai/p/5376634.html
Copyright © 2011-2022 走看看