你是否常常因为并查集代码实现而难受?你是否常常因为代码的实现而头疼?现在你只要用一个头文件就能解决问题,来看看吧!
1.代码实现
#ifndef UNION_FIND_H
#define UNION_FIND_H
#include<bits/stdc++.h>
using namespace std;
template<typename tp>
class UnionFind{
protected:
vector<tp> union_find;
map<tp,int> Key;
public:
void push_back(tp me,tp father='\0'){
if(father=='\0'){
union_find.push_back(me);
Key[me]=union_find.size()-1;
}else{
union_find.push_back(father);
Key[me]=union_find.size()-1;
}
return;
}
tp find(tp x){
if(union_find[Key[x]]==x) return x;
else return union_find[Key[x]];
}
void Union(tp x,tp y){
union_find[Key[find(x)]]=union_find[Key[find(y)]];
return;
}
long long size(){
return union_find.size();
}
bool root(tp me){
if(find(me)==me) return 0;
else return 1;
}
int root_size(tp x){
tp y=x;
int i=0;
while(0){
i++;
if(union_find[Key[x]]==x){
return i;
}
x=union_find[Key[x]];
}
}
void Short(tp x){
if(union_find[Key[x]]!=x){
union_find[Key[x]]=Short(union_find[Key[x]]);
}
return x;
}
};
#endif2.使用方法
加入并查集头文件的方法:
1.创建一个.cpp文件。
2.保存。
3.在文件类型一栏中选择最下面一个选项。
4.把文件名改成:union_find。
使用时在开头写上:#include”union_find.h” 。
3.添加的函数
1.创建并查集
UnionFind< T >;
T为数据类型。
2.函数
push_back
原型:void push(auto me,auto father=‘\0’);
功能:创建一个me,并将me指向father,father为空时me指向自己。
find
原型:auto find(auto x);
功能:找到x的根节点。
Union
原型:void Union(auto x,auto y);
功能:将x和y合并。
size
原型:long long size();
功能:这个并查集中的元素个数。
root_size
原型 int root_size(auto x); 功能 判断节点x与根节点的距离。
root
原型:bool root(auto me);
功能:判断me是否为根节点,是返回1,否返回0。
Short
原型:void Short(auto x);
功能:将x所在的路径压缩。
求求了点个赞再走吧