码迷,mamicode.com
首页 > 其他好文 > 详细

并查集

时间:2016-04-11 01:34:08      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

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

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

 

并查集

标签:

原文地址:http://www.cnblogs.com/wangdongkai/p/5376634.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!