并查集检测成环
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yQUJ7dkg-1612703584095)(C:\Users\左泽平\Desktop\无标题.png)]
#include<bits/stdc++.h>
using namespace std;
# define vertices 6
int parent[vertices];
void init(int a[])
{
for(int i = 0 ; i <vertices ; i ++)
{
parent[i] = -1;
}
}
int find_root(int x ,int father[])
{
int x_root = x;
while( parent[x_root] != -1)
{
x_root = parent[x_root];
}
return x_root;
}
int union_vertices(int x , int y, int parent[])
{
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()
{
init(parent);
int edge[6][2]={ {0,1} ,{2,4},{1,2},{1,3},{2,5},{3,4}};
for(int i = 0 ; i < 6 ; i ++){
int x = edge[i][0];
int y = edge[i][1];
if( union_vertices( x , y , parent ) == 0) {
cout<<" circle dectect"<<endl;
exit(0);
}
}
cout << " NOT dectect"<<endl;
return 0;
}
压缩路径
根据树的高度(rank)来合成树
改进后的代码
#include<bits/stdc++.h>
using namespace std;
# define vertices 6
int parent[vertices];//树的深度
int rank_[vertices]={0};
void init(int a[])
{
for(int i = 0 ; i <vertices ; i ++)
{
parent[i] = -1;
}
}
int find_root(int x ,int father[])
{
int x_root = x;
while( parent[x_root] != -1)
{
x_root = parent[x_root];
}
return x_root;
}
int union_vertices(int x , int y, int parent[],int rank_[])
{
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;
if( rank_[x_root] > rank_[y_root]){
parent[y_root] = x_root;
}
else if ( rank_[y_root] > rank_[x_root]){
parent[x_root] = y_root;
}
else{
parent[x_root] = y_root;
rank_[y_root]++;
}
return 1;
}
}
int main()
{
init(parent);
int edge[6][2]={ {0,1} ,{2,4},{1,2},{1,3},{2,5},{3,4}};
for(int i = 0 ; i < 6 ; i ++){
int x = edge[i][0];
int y = edge[i][1];
if( union_vertices( x , y , parent,rank_) == 0) {
cout<<" circle dectect"<<endl;
exit(0);
}
}
cout << " NOT dectect"<<endl;
return 0;
}
" circle dectect"<<endl;
exit(0);
}
}
cout << " NOT dectect"<<endl;
return 0;
}