資源簡介
使用C++實現了并查集的建立,合并和查找功能,并附簡單的測試用例。
代碼片段和文件信息
//并查集的C++實現
#include
#include
#include
using?namespace?std;
const?int?MAX=100;
/*?father[x]表示x的父節點?*/
int?father[MAX];
/*?rank[x]表示x的秩?*/
int?rank[MAX];
/*?初始化集合?*/
void?Make_Set(int?x)
{
father[x]?=?x;
rank[x]?=?0;
}
/*?查找x元素所在的集合回溯時壓縮路徑?*/
int?Find_Set(int?x)
{
if?(x?!=?father[x])
{
father[x]?=?Find_Set(father[x]);
}
return?father[x];
}
/*?按秩合并xy所在的集合?*/
void?Union(int?x?int?y)
{
x?=?Find_Set(x);
y?=?Find_Set(y);
if?(x?==?y)?return;
if?(rank[x]?>?rank[y])
{
father[y]?=?x;
}
else
{
if?(rank[x]?==?rank[y])
{
rank[y]++;
}
father[x]?=?y;
}
}
int?main()
{
list?>?l;
vector?temp;
temp.push_back(1);
temp.push_back(2);
temp.push_back(3);
l.push_back(temp);
temp.clear();
temp.push_back(2);
temp.p
- 上一篇:校園導游圖(C++)
- 下一篇:mfc 課程設計 view 瀏覽器 收藏夾
評論
共有 條評論