并查集

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

#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;
}

 

posted @ 2016-04-11 00:07  季末Despair  阅读(157)  评论(0编辑  收藏  举报