关注
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;
}
查看原帖
点赞 评论
相关推荐
点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 你实习是赚钱了还是亏钱了? #
30479次浏览 241人参与
# 2022毕业即失业取暖地 #
116578次浏览 705人参与
# 联影求职进展汇总 #
51368次浏览 325人参与
# 用一句话形容你的团队氛围 #
18588次浏览 179人参与
# CVTE求职进展汇总 #
23139次浏览 320人参与
# 你找工作是从容有余 or 匆忙滚爬? #
12123次浏览 94人参与
# 京东开奖 #
471440次浏览 2679人参与
# 哪些公司校招卡第一学历 #
220337次浏览 777人参与
# 牛客租房专区 #
122969次浏览 1347人参与
# 机械人与华为的爱恨情仇 #
137428次浏览 1013人参与
# 海康威视工作体验 #
45729次浏览 157人参与
# 腾讯音乐求职进展汇总 #
136166次浏览 1005人参与
# 嵌入式岗知多少 #
58811次浏览 548人参与
# 联影医疗求职进展汇总 #
6217次浏览 25人参与
# 毕业论文进行时 #
6851次浏览 81人参与
# 同bg的你秋招战况如何? #
174776次浏览 1021人参与
# 找实习你看重大厂光环还是业务方向 #
41605次浏览 164人参与
# 58同城求职进展汇总 #
40280次浏览 263人参与
# 我来点评面试官 #
16668次浏览 114人参与
# 面对逼签的应对技巧 #
7204次浏览 37人参与
# 扒一扒那些奇葩实习经历 #
126853次浏览 1100人参与
