求图的连通分量个数

前言

求图的连通分量个数在算法题中时有考到,是图算法中基础而重要的问题。对于这个问题,常用的解法有搜索算法(DFS、BFS等),及并查集算法。图的搜索算法在我的其他博文中已经介绍过,这里用一个例题介绍一下并查集求连通分量个数的方法。
对并查集算法不了解的同学可以看我的博文:并查集

例题

题目链接:https://www.luogu.com.cn/problem/P1536
在这里插入图片描述在这里插入图片描述

AC代码

#include<iostream>
#include<cstring>
using namespace std;
int father[1000];
int find(int x){
	while(father[x]!=-1) x=father[x];
	return x;
}
void Union(int a,int b){
	int fa=find(a),fb=find(b);
	if(fa!=fb){
		father[fa]=fb;
	}
}
int main() {
	int n,m;
	while(cin>>n>>m){
		memset(father,-1,sizeof(int)*(n+1));
		int a,b,ans=0;
		while(m--){
			cin>>a>>b;
			Union(a,b);
		}
		for(int i=1;i<=n;i++){
			if(father[i]==-1) ans++;
		}
		cout<<ans-1<<endl;
	}
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章