关注
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;
}
查看原帖
点赞 评论
相关推荐
点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 烂工作和没工作哪个更痛苦? #
10831次浏览 198人参与
# Tplink求职进展汇总 #
214135次浏览 975人参与
# 厦门银行科技岗值不值得投 #
17660次浏览 419人参与
# 面试体验最好和最差的公司 #
12765次浏览 77人参与
# 携程工作体验 #
27198次浏览 103人参与
# 给工作过的公司写一条大众点评,你会怎么写? #
4244次浏览 59人参与
# 你找工作想离家近 or 离家远? #
45404次浏览 357人参与
# 我是XXX,请攻击我最薄弱的地方 #
70184次浏览 450人参与
# 实习心态崩了 #
112206次浏览 600人参与
# 春招至今,你收到几个面试了? #
30115次浏览 444人参与
# Agent面试会问什么? #
9680次浏览 272人参与
# 一人分享一个skill #
2266次浏览 66人参与
# 秋招吐槽大会 #
324840次浏览 1586人参与
# AI替代不了什么? #
8341次浏览 115人参与
# 技术转行的心路历程 #
92119次浏览 783人参与
# 职场中那些令人叹为观止的八卦 #
105530次浏览 489人参与
# 如何提高实习转正率? #
102074次浏览 622人参与
# 现在入门AI首先要做什么? #
2315次浏览 60人参与
# 学历VS实习,哪个更重要? #
22339次浏览 292人参与
# 网易游戏笔试 #
11161次浏览 94人参与
# 我的求职进度条 #
963784次浏览 6423人参与
