Is there a ring (and check set)

Is there a ring

Insert picture description here
Insert picture description here

#include <bits/stdc++.h>
#include <string.h>
using namespace std;

/*
LeeG
2020/8/5 15:25 
*/

/*
并查集
1. 初始化parent数组
2. 合并
3. 寻找祖先 
*/ 

/*
通过数据结构并查集解决一个实际问题:判断一个连通图中是否有环 
输入样例:
11 11
0 1
0 9
1 2
1 3
2 4
2 5
3 7
4 8
5 6
6 10
9 10
输出: No cycle found.
*/

int find_root(int x, int parent[]){	//第三步find_root()函数, 寻找祖先 
	int x_root =  x;
	while(parent[x_root] != -1){
		x_root = parent[x_root];
	}
	return x_root;
}

int union_funtion(int x, int y, int parent[]){	//第二步union_funtion, 将两个元素合并 
	int x_root = find_root(x, parent);	   
	int y_root = find_root(y, parent);
	if(x_root == y_root) return 0; //合并失败,因为已经在同一集合中了
	else parent[x_root] = y_root;
	return 1;
}

int main(){
	int n, m;
	cin>>n>>m;
	int parent[n];
	memset(parent, -1, sizeof(parent));		//第一步初始化parent数组 
	int edges[n][2];
	for(int i = 0; i < m; i++){
		cin>>edges[i][0]>>edges[i][1];
	}
	int flag = 0;
	for(int i = 0; i < m; i++){
		if(union_funtion(edges[i][0], edges[i][1], parent) == 0){
			flag = 1;
			break;
		}
	}
	if(flag == 0) cout<<"No cycle found.";
	else cout<<"Cycle detected!";
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_44723496/article/details/109100578