并查集

#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值