并查集(Disjoint Set)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LightInDarkness/article/details/86325825
#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

猜你喜欢

转载自blog.csdn.net/LightInDarkness/article/details/86325825