King Way_Example 11.2 Judging Connected Graphs (Union Check Set)

Application of Union Check Set on Connected Graph

Connected graph definition: In the undirected graph G , if there is a path from vertex u to vertex v, u and v are said to be connected. If any two points in the graph are connected , the graph is called a connected graph .

Connected component: A maximal connected subgraph in the undirected graph G is called a connected component of G, and the connected graph has only one connected component, which is itself.

Ideas

Continuously merge the sets of the two points connected by the edges in the graph, and finally calculate the number of sets to be the number of connected components. The connected component is a connected graph.

Code

//判断无向图是否为连通图
#include <iostream>
using namespace std;
const int MAXN=1000;
int father[MAXN];//记录父节点 
int height[MAXN];//记录高度 
void Initial(int n)
{
    
    
	for(int i=0;i<n;++i)
	{
    
     
		father[i]=i;//初始时节点的父亲为节点本身 
		height[i]=0; 
	} 
}
//查找父节点,最终返回父节点 
int Find(int x)
{
    
    
	if(x!=father[x])
	{
    
    
		father[x]=Find(father[x]);
	}
	return father[x];
 }
 //合并节点 
 void Union(int x,int y)
 {
    
    
 	x=Find(x);
	y=Find(y);
	//两个节点不在同一个集合中时 
	if(x!=y)
	{
    
    
		if(height[x]>height[y])
			father[y]=x;
		else if(height[x]<height[y])
			father[x]=y;
		else
		{
    
    	father[x]=y;
			height[x]++;} 
	 } 
  } 
int main()
{
    
    
	int n,m;//顶点数 边数
	while(cin>>n)
	{
    
    
		cin>>m;
		if(n==0) break;
		Initial(n);//初始化,初始所有的顶点是孤立的
		while(m--)
		{
    
    
			int x,y;
			cin>>x>>y;//输入边
			Union(x,y);//集合合并 
		 } 
		int number=0;
		for(int i=0;i<n;++i)
		{
    
    
			if(Find(i)==i) ++number; 
		 } 
		if(number==1) cout<<"YES"<<endl;
		else cout<<"NO"<<endl;
	 } 
 } 

Guess you like

Origin blog.csdn.net/weixin_45019830/article/details/115010866