题解 | 第一题

#include<iostream>

using namespace std;
const int maxn = 1000005;
int f[maxn];
int h[maxn];
bool p[maxn];
void init(){
	for(int i=0;i<maxn;i++){
		f[i] = i;
		h[i] = 0;
		p[i] = false;
	}
}
int find(int x){
	if(x!=f[x]){
		f[x] = find(f[x]);
	}
	return f[x];
}
void uniond(int x,int y){
	if(h[x]>h[y]){
		f[y] = x;
	}else if(h[y]>h[x]){
		f[x] = y;
	}else{
		f[y] = x;
		h[x]++;
	}
}
int main(){
	int n,m;
	init();
	while(cin>>n>>m){
		int c = find(n);
		int d = find(m);
		if(c!=d)uniond(c,d);
		p[n] = true;
		p[m] = true;
	}
	int num = 0;
	for(int i=0;i<maxn;i++){
		if(!p[i])continue;
		if(f[i]==i)num++;
	}
	cout<<num<<endl;
}

全部评论

相关推荐

ohs的小木屋:比不少实习待遇高了
点赞 评论 收藏
分享
06-26 15:33
青岛工学院 Java
积极的秋田犬要冲国企:他现在邀请我明天面试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务