您的位置:首页 > 其它

并查集 - 模板

2017-03-23 18:23 387 查看
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[ancestor2], rank[ancestor1] + 1);
return true;
}
return false;
}
int find_father(int node)
{
return father[node];
}
};


2017 - 3 - 23 

NOIP Day 232
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: