关注
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;
}
查看原帖
点赞 评论
相关推荐
点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 哪些公司在招寒假实习? #
17394次浏览 220人参与
# 卷__卷不过你们,只能卷__了 #
12847次浏览 278人参与
# MiniMax求职进展汇总 #
815次浏览 23人参与
# 26年哪些行业会变好/更差 #
20012次浏览 272人参与
# 写论文的崩溃时刻 #
7042次浏览 152人参与
# 你不能接受的企业文化有哪些 #
12945次浏览 179人参与
# 你觉得面试是靠实力还是靠运气 #
26647次浏览 283人参与
# 去年的flag与今年的小目标 #
10634次浏览 202人参与
# 互联网行业现在还值得去吗 #
49271次浏览 361人参与
# 有深度的简历长什么样? #
17320次浏览 356人参与
# 关于春招你都做了哪些准备? #
122307次浏览 709人参与
# 入职第一天 #
10596次浏览 227人参与
# 你都用AI做什么 #
7260次浏览 164人参与
# 国企vs私企,你更想去? #
306070次浏览 2492人参与
# 腾讯音乐求职进展汇总 #
148169次浏览 1054人参与
# 租房前辈的忠告 #
350648次浏览 7448人参与
# 产品人求职现状 #
309772次浏览 2397人参与
# 一人分享一道面试手撕题 #
24654次浏览 848人参与
# 你怎么看待AI面试 #
133529次浏览 746人参与
# 十一月总结 #
70619次浏览 409人参与
# 现在前端的就业环境真的很差吗 #
494313次浏览 6003人参与
SHEIN希音公司福利 294人发布
