关注
mywgo
并查集的板子
#include<iostream>
(30316)#include<vector>
#include<map>
(30192)#include<algorithm>
using namespace std;
map<int,int> father; //通过散列表map实现的father数组
map<int,int> height; //记录每个节点的高度
int find(int x){
if(father.find(x)!=father.end()){
if(father[x]!=x)
father[x]=find(father[x]); //路径压缩(最后自己通过例子模拟下过程)
}
else{//如果还没有出现的新节点。把father设成他自己(表示根节点),height设成0
father[x]=x;
height[x]=0;
}
return father[x];
}
void Union(int a,int b){//合并函数
a=find(a);
b=find(b);
if(a!=b){
if(height[a]>height[b])
father[b]=a;
else if(height[b]>height[a])
father[a]=b;
else{
father[a]=b;
height[a]++;
}
}
}
int main()
{
int i,j;
while(cin>>i>>j){
Union(i,j);
}
int sum=0;
for(auto it=father.begin();it!=father.end();it++){
if(it->first==it->second)sum++; //只要有一个父亲是本身的就说明是根节点
}
cout<<sum<<endl;
return 0;
}
查看原帖
点赞 评论
相关推荐
牛客热帖
更多
正在热议
更多
# 你的实习产出是真实的还是包装的? #
35182次浏览 433人参与
# 牛友的志愿填报指南 #
63010次浏览 484人参与
# 厦门银行科技岗值不值得投 #
15689次浏览 359人参与
# 你的实习什么时候入职 #
366778次浏览 2355人参与
# 学历VS实习,哪个更重要? #
1750次浏览 49人参与
# 工作上你捅过哪些篓子? #
68317次浏览 315人参与
# uu们,春招你还来吗? #
63141次浏览 739人参与
# 面试紧张时你会有什么表现? #
34043次浏览 207人参与
# 面试中,你被问过哪些奇葩问题? #
96229次浏览 1264人参与
# 面试被问到不会的问题,你怎么应对? #
25876次浏览 648人参与
# 你都用vibe coding做过什么? #
21842次浏览 816人参与
# 机械人,签完三方你在忙什么? #
83932次浏览 266人参与
# 你觉得大几开始实习最合适? #
30034次浏览 309人参与
# AI Coding实战技巧 #
15425次浏览 299人参与
# 你见过哪些招聘隐形歧视? #
24870次浏览 214人参与
# 国庆前的秋招小结 #
291250次浏览 1742人参与
# 哔哩哔哩笔试 #
35138次浏览 142人参与
# 如果人生可以debug你会改哪一行? #
13010次浏览 167人参与
# 秋招特别不鸣谢 #
93224次浏览 685人参与
# 应届生被毁约被毁意向了怎么办 #
65374次浏览 313人参与
# 海康威视求职进展 #
132284次浏览 551人参与
查看8道真题和解析
