关注
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;
}
查看原帖
点赞 评论
相关推荐
03-30 23:28
西安邮电大学 Java 点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 面试被问到不会的问题,你怎么应对? #
23967次浏览 596人参与
# 牛友的志愿填报指南 #
62746次浏览 479人参与
# 厦门银行科技岗值不值得投 #
15468次浏览 355人参与
# 你觉得大几开始实习最合适? #
27849次浏览 271人参与
# uu们,春招你还来吗? #
61777次浏览 704人参与
# 你见过哪些招聘隐形歧视? #
23193次浏览 196人参与
# 招商银行数字金融训练营 #
106725次浏览 917人参与
# 面试中,你被问过哪些奇葩问题? #
95499次浏览 1229人参与
# 学历VS实习,哪个更重要? #
1285次浏览 37人参与
# 你都用vibe coding做过什么? #
20474次浏览 777人参与
# AI Coding实战技巧 #
14775次浏览 292人参与
# 哔哩哔哩笔试 #
34933次浏览 142人参与
# 如果人生可以debug你会改哪一行? #
12335次浏览 157人参与
# 海康威视求职进展 #
132185次浏览 551人参与
# 你现在一天AI几次? #
12676次浏览 126人参与
# 机械人你觉得今年行情怎么样? #
7817次浏览 96人参与
# 面试紧张时你会有什么表现? #
33688次浏览 201人参与
# Claude Code泄露源码 #
14724次浏览 201人参与
# 做完笔试后你收到面试了吗? #
25003次浏览 214人参与
# 恒生电子笔试 #
20817次浏览 156人参与
# Vibe Coding 会干掉初级岗位吗? #
21747次浏览 218人参与
# 机械人,签完三方你在忙什么? #
83769次浏览 265人参与
查看2道真题和解析