并查集 模板

并查集是高效的查询两个元素是否属于一个集合的方法,为了使用方便把关系并查集和并查集利用面向对象和泛型编程的思想写在了一起。

template <typename Type>
class DisjointSet {
    struct node {
        int parent_;
        Type relation_; //parent -> this
    };

    vector<node> nodes;
    vector<int> parents;

public:
    bool is_relation_;

    DisjointSet(int number_nodes, bool is_relation = false) {
        is_relation_ = is_relation;

        if(is_relation_) {
            nodes.resize(number_nodes+1);
            for(int i = 0; i <= number_nodes; ++i) {
                nodes[i].parent_ = i;
                nodes[i].relation_ = 0;
            }
        } else {
            parents.resize(number_nodes+1);
            for(int i = 0; i <= number_nodes; ++i)
                parents[i] = i;
        }
    }

    int find(int x) {
        if(is_relation_) {
            if(nodes[x].parent_ != x) {
                int xparent = nodes[x].parent_; // x's old parent
                nodes[x].parent_ = find(nodes[x].parent_);
                nodes[x].relation_ = nodes[x].relation_ + nodes[xparent].relation_;
            }
            return nodes[x].parent_;
        } else {
            if(parents[x] != x)
                parents[x] = find(parents[x]);
            return parents[x];
        }
    }

    Type get_relation(int x) {
        return nodes[x].relation_;
    }

    void merge(int x, int y) {
        parents[find(y)] = find(x);
    }

    void merge(int x, int y, Type relation) {
        // relation: x->y
        int yparent = find(y);
        nodes[yparent].parent_ = find(x);
        nodes[yparent].relation_ = nodes[x].relation_ + relation - nodes[y].relation_;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值