关注
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;
}
查看原帖
点赞 评论
相关推荐
点赞 评论 收藏
分享
07-11 11:50
门头沟学院 运营 点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 技术岗笔试题求解 #
77594次浏览 1005人参与
# 拼多多求职进展汇总 #
642344次浏览 4983人参与
# 工作一周年分享 #
30698次浏览 179人参与
# 如果公司给你放一天假,你会怎么度过? #
16249次浏览 122人参与
# 作业帮求职进展汇总 #
55758次浏览 370人参与
# 华子oc时间线 #
1236418次浏览 6473人参与
# OPPO求职进展汇总 #
662176次浏览 5032人参与
# 总结:哪家公司面试体验感最差 #
60475次浏览 273人参与
# 职场上哪些事情令人讨厌 #
18719次浏览 91人参与
# 三一重工求职进展汇总 #
14313次浏览 65人参与
# 去年你投递实习了吗? #
21991次浏览 329人参与
# 这些公司卡简历很严格 #
41287次浏览 204人参与
# 扒一扒那些奇葩实习经历 #
66306次浏览 913人参与
# 经纬恒润求职进展汇总 #
121666次浏览 1032人参与
# 提前批过来人的忠告 #
113858次浏览 1194人参与
# 说说你知道的学历厂 #
58378次浏览 351人参与
# 秋招最大的收获是什么? #
36871次浏览 311人参与
# 找工作时的取与舍 #
80011次浏览 566人参与
# 你认为小厂实习有用吗? #
29311次浏览 341人参与
# 哪一瞬间觉得自己长大了 #
13908次浏览 327人参与