1118 Birds in Forest (25分) / 並查集

題目描述

在這裏插入圖片描述
在這裏插入圖片描述

知識點詳解

主要考察並查集的知識,這裏已經爲大家整理好的,想複習的同學點這裏

AC代碼

#include<bits/stdc++.h>
using namespace std;
int father[10005];
int find(int x){
	while(father[x]>=0){
		x=father[x];
	}
	return x;
}
void Union(int a,int b){
	int fa=find(a),fb=find(b);
	if(fa!=fb){					//按秩歸併 
		if(father[fa]<father[fb]){
			father[fa]+=father[fb];
			father[fb]=fa;
		}
		else{
			father[fb]+=father[fa];
			father[fa]=fb;
		}
	}
}
int main() {
	memset(father,-1,sizeof(father)); //注意初始化 
	int n,maxnum=0;cin>>n;
	while(n--){
		int k,root,temp;cin>>k;
		for(int i=0;i<k;i++){
			scanf("%d",&temp);
			maxnum=max(maxnum,temp);  //更新birds id的最大值 
			if(i==0) root=temp;  //將每張圖片的第一隻bird作爲根結點 
			else Union(temp,root);
		}
	}
	int cnt=0,num=0;
	for(int i=1;i<=maxnum;i++){
		if(father[i]<0) {
			cnt++;       //集合個數 
			num-=father[i];    //number of birds
		}
	}
	printf("%d %d\n",cnt,num);
	int k;cin>>k;
	while(k--){
		int a,b;
		scanf("%d%d",&a,&b);
		printf("%s\n",find(a)==find(b)?"Yes":"No");
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章