关注
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;
}
查看原帖
点赞 评论
相关推荐
04-01 21:46
北京邮电大学 Java 梦雨雨:强烈推荐!这个笔记写得很清晰 http://github.com/AccumulateMore/CV
查看1道真题和解析 点赞 评论 收藏
分享
03-24 23:51
门头沟学院 测试开发 点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 你的实习产出是真实的还是包装的? #
34935次浏览 433人参与
# 牛友的志愿填报指南 #
62971次浏览 484人参与
# 厦门银行科技岗值不值得投 #
15646次浏览 359人参与
# 你的实习什么时候入职 #
366665次浏览 2355人参与
# 学历VS实习,哪个更重要? #
1617次浏览 48人参与
# 工作上你捅过哪些篓子? #
68295次浏览 315人参与
# uu们,春招你还来吗? #
62926次浏览 738人参与
# 面试紧张时你会有什么表现? #
33947次浏览 206人参与
# 面试中,你被问过哪些奇葩问题? #
96106次浏览 1263人参与
# 面试被问到不会的问题,你怎么应对? #
25661次浏览 648人参与
# 你都用vibe coding做过什么? #
21639次浏览 812人参与
# 机械人,签完三方你在忙什么? #
83902次浏览 266人参与
# 你觉得大几开始实习最合适? #
29852次浏览 309人参与
# AI Coding实战技巧 #
15280次浏览 299人参与
# 你见过哪些招聘隐形歧视? #
24581次浏览 214人参与
# 国庆前的秋招小结 #
291204次浏览 1742人参与
# 哔哩哔哩笔试 #
35089次浏览 142人参与
# 如果人生可以debug你会改哪一行? #
12858次浏览 167人参与
# 秋招特别不鸣谢 #
93204次浏览 685人参与
# 应届生被毁约被毁意向了怎么办 #
65325次浏览 313人参与
# 海康威视求职进展 #
132273次浏览 551人参与
