求圖的連通分量個數

前言

求圖的連通分量個數在算法題中時有考到,是圖算法中基礎而重要的問題。對於這個問題,常用的解法有搜索算法(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;
}

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