关注
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;
}
查看原帖
点赞 评论
相关推荐


点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 从顶到拉给所有面过的公司评分 #
45353次浏览 292人参与
# 产品薪资爆料 #
131102次浏览 838人参与
# 宣讲会你有哪些意向不到的收获 #
6005次浏览 42人参与
# 签约/解约注意事项 #
722992次浏览 4103人参与
# 聊聊这家公司值得去吗 #
582236次浏览 3819人参与
# 小厂实习有必要去吗 #
56601次浏览 285人参与
# 水滴求职进展汇总 #
6349次浏览 32人参与
# 你怎么评价今年的春招? #
131042次浏览 1369人参与
# 机械制造岗投递时间线 #
28213次浏览 372人参与
# 为了求职,我做过的疯狂伪装 #
21009次浏览 456人参与
# 十一假期一定要干的事 #
18280次浏览 145人参与
# 你的国庆怎么过 #
27559次浏览 253人参与
# 工作压力大怎么缓解 #
107929次浏览 1072人参与
# 晒晒你的中秋福利 #
18975次浏览 137人参与
# bilibili求职进展汇总 #
100872次浏览 864人参与
# 职场破冰,你们都聊什么? #
11838次浏览 97人参与
# 你面试被问到过哪些不会的问题? #
39339次浏览 1078人参与
# 秋招的嫡长offer #
54394次浏览 455人参与
# 顺丰求职进展汇总 #
56850次浏览 290人参与
# 机械笔面试考察这些知识点 #
12683次浏览 96人参与