プロセス分析のいかなるリングありません。
する#include <stdio.hに>
する#include <STDLIB.H>
の#include <入出力ストリーム>
。の#define頂点6
。の#define LINE 5
使用名前空間STD;
/ *
親:アレイを設定し、問題を解決し、チェック
頂点:頂点の数設定
ライン:エッジ数設定
* /
ボイド初期化(INT *親)
{
アレイ親初期化する//を
I intを、
ため(I = 0; Iは、頂点を<; Iは++)
{
。親[I] = - 1;
}
}
find_rootは整数(INTのX、親INT [])
{
//がルートを見つけるために使用される
INT x_root = Xを、
(!親[x_root] = -1)、一方
{
x_root =親[x_root];
}
戻りx_root;
}
([] int型X、Yはint、int型の親)は、INT union_vertices
};
(; Iは、ラインを<I ++はI = 0の整数)のための
{
{
//二組をマージします。0を返します:合併が成功し、リターン1:マージ失敗した
int型x_root = find_rootは(X-、親);
int型y_root = find_rootは(y軸、親);
のprintf(「X-:現在の数は、彼の親は%dですされます。%D \ N- "X、x_root);
のprintf(" Y:現在の番号%dであり、彼の親である:D%\ N-」、Y、y_root);
IF(x_root == y_root)
{
0を返す;
}
他
{
親【x_root] = y_root; // XのYに接続されている
。リターン1;
}
}
int型のmain()
{
int型の親[頂点] = {0};
(親)を初期化し、
エッジ[LINE]をINT [2] = {
{ } 0.1、{1,2}、{1,3}、
{2,4}、{2,5}
INT X =縁[i]が[0]。
Y = INTエッジ[I] [1]。
IF(union_vertices(X、Y、親)== 0)
{
のprintf( "存在の环")。
出口(0);
}
}
のprintf( "没有の环")。
0を返します。
}
リングのプロセス解析プレゼンス:
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#define VERTICES 6
#define LINE 6
using namespace std;
/*
parent:数组解决并查集合并问题
VERTICES:设定的顶点数
LINE:设定的边数
*/
void initialise(int *parent)
{
//用于parent数组的初始化
int i;
for(i=0;i<VERTICES;i++)
{
parent[i]=-1;
}
}
int find_root(int x,int parent[])
{
//用来查找根节点
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[])
{
//用于合并两个集合 。返回0:合并成功,返回1:合并失败
int x_root=find_root(x,parent);
int y_root=find_root(y,parent);
printf("x:当前数是%d,他的parent是:%d\n",x,x_root);
printf("y:当前数是%d,他的parent是:%d\n",y,y_root);
if(x_root==y_root)
{
return 0;
}
else
{
parent[x_root]=y_root;//将x连到y上
return 1;
}
}
int main()
{
int parent[VERTICES]={0};
initialise(parent);
int edges[LINE][2] = {
{0,1},{1,2},{1,3},
{2,4},{2,5},{3,4}
};
for(int i=0;i<LINE;++i)
{
int x=edges[i][0];
int y=edges[i][1];
if(union_vertices(x,y,parent)==0)
{
printf("存在环");
exit(0);
}
}
printf("没有环");
return 0;
}
最后一次没有执行“parent[x_root]=y_root;”