并查集(Disjoint Set)

本文介绍了一种使用并查集算法检测图中是否存在环的方法。通过初始化并查集,然后遍历每条边,利用FindRoot和Union函数判断是否形成环。若在并集中发现两个节点已经在同一集合,则说明存在环。此算法适用于无向图的环检测。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>

using namespace std;

#define VERTICLES 6

void Initialise(int parent[], int rank[]){
	for(int i = 0; i < VERTICLES; i++){
		parent[i] = -1;
		rank[i] = 0;
	}
}

int FindRoot(int x, int parent[]){
	while(parent[x] != -1){
		x = parent[x];
	}
	return x;
}

/*
If the return value is 1, the union is successful, and
the parent of x is y.
If 0, the union failed.
*/
int Union(int x, int y, int parent[], int rank[]){
	int x_root = FindRoot(x, parent);
	int y_root = FindRoot(y, parent);
	if(x_root == y_root){
		return 0;
	}else{
		//parent[x_root] = y_root;
		if(rank[x_root] > rank[y_root]){
			parent[y_root] = x_root;
		}else if(rank[x_root] < rank[y_root]){
			parent[x_root] = y_root;
		}else{
			//To avoid list-like trees
			parent[x_root] = y_root;
			rank[y_root]++;
		}
		return 1;
	}
}

int main(){
	int parent[VERTICLES];
	int rank[VERTICLES];
	int edges[6][2] = {{0, 1}, {1, 2}, {1, 3}, {2, 4}, {3, 4}, {2, 5}};
	Initialise(parent, rank);
	for(int i = 0; i < 6; i++){
		int x = edges[i][0];
		int y = edges[i][1];
		if(Union(x, y, parent, rank) == 0){
			cout << "Cycle detected." << endl;
			exit(0);
		}
	}
	cout << "No cycles found." << endl;
	return 0;
}

参考:https://www.bilibili.com/video/av38498175?p=3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值