#include<iostream>
using namespace std;
const int MAX_SIZE = 1000;
void init_set(int parent[],int high[])
{
for (int i = 0; i < MAX_SIZE; ++i)
{
parent[i] = -1; //初始化节点高度和根节点
high[i] = 0;
}
}
//通过递归实现将所有节点都指向根节点,降低查找时间复杂度为O(1)
int find_root(int x, int parent[])
{
int root = x;
while (parent[root] != -1)
{
root = find_root(parent[root],parent);
}
return root;
}
// 0 - 表示形成有环,1 - 表示形成无环
int union_section(int x, int y, int parent[], int high[])
{
int x_root = find_root(x, parent);
int y_root = find_root(y, parent);
if (x_root == y_root) return 0;
//if (parent[x] == -1)
//{
// parent[x] = y;
// cout << x << " " << parent[x] << endl;
//}
//else
//{
// parent[y] = x; //x,y不在一个环中,则连接它们
// cout << y<<" "<< parent[y] << endl;
//}
else
{
if (high[x_root] > high[y_root]) parent[y_root] = x_root;
else
{
parent[x_root] = y_root;
if (high[x_root] == high[y_root]) high[y_root]++;
}
}
cout << x_root << parent[x_root] << endl;
return 1;
}
int main()
{
int edges[5][2] = {
{1,2},{6,2},
{1,4},{4,5},{5,3}
};
int parent[MAX_SIZE], high[MAX_SIZE];
init_set(parent,high);
for (int i = 0; i < 5; i++)
{
if (!union_section(edges[i][0], edges[i][1], parent,high))
{
cout << "cycle detected!!!" << endl;
system("pause");
return 0;
}
}
cout << "NO Cycle." << endl;
system("pause");
return 0;
}
并查集
最新推荐文章于 2023-05-12 16:29:23 发布