1 Star 0 Fork 0

jiangmiao/jiangm2022

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
UnionFind.cpp 1.50 KB
一键复制 编辑 原始数据 按行查看 历史
Your Name 提交于 2022-11-09 10:01 . 加入数据结构代码
#include "UnionFind.h"
#include<iostream>
using namespace std;
int UnionFind::getunioncount()
{
return unionsize.size();
}
UnionFind::UnionFind(vector<int> myList)//캯
{
for (int val : myList) {
element* ele = new element(val);
elements[val] = ele;
fathers[ele] = ele;
unionsize[ele] = 1;
}
}
element* UnionFind::findroot(element* c_element)
{
stack<element *> stk;
element* ele = c_element;
element* father = fathers[ele];
while (ele != father) {
stk.push(ele);
ele = father;
father = fathers[ele] ;
}
while (!stk.empty()) {
fathers[stk.top()] = father;
stk.pop();
}
return father;
}
bool UnionFind::issameset(int a, int b)
{
if (elements.find(a) != elements.end() && elements.find(b) != elements.end()) {
if (findroot(elements[a]) == findroot(elements[b])) {
return true;
}
}
return false;
}
void UnionFind::Union(int a, int b)
{
if (elements.find(a) != elements.end() && elements.find(b) != elements.end()) {
if (!issameset(a,b)) {
element* atopleader = findroot(elements[a]);
element* btopleader = findroot(elements[b]);
int arootsize = unionsize[elements[a]];
int brootsize = unionsize[elements[b]];
element* big = arootsize >= brootsize ? atopleader : btopleader;
element* small = big == atopleader ? btopleader : atopleader;
fathers[small] = big;
unionsize[big] = arootsize + brootsize;
unionsize.erase(small);
}
}
}
void UnionFind::print()
{
for (auto p : unionsize) {
cout << p.first->value << "ԱΪ" << p.second << endl;
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/gingerj/jiangm2022.git
[email protected]:gingerj/jiangm2022.git
gingerj
jiangm2022
jiangm2022
master

搜索帮助