题解 | #第一题#

第一题

https://www.nowcoder.com/practice/7c29cdfa28274c86afc9e88c07448a10

#include <iostream>
#include <cstring>
#include <vector>
#include <unordered_set>
#include<map>
using namespace std;
map<int,int> s;
int find(int x){
    while(s[x]>0){
        x=s[x];
    }
    return x;
}
void union1(int r1,int r2){
    s[r1]=r2;
}
int main() {
    int a, b;
    while (cin >> a >> b) { // 注意 while 处理多个 case

        int r1=find(a),r2=find(b);
        if(r1!=r2) union1(r1,r2);
    }
    int res=0;unordered_set<int> ans;
    for(auto it:s){
        ans.insert(find(it.first));
    }
cout<<ans.size();
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

11-06 23:30
已编辑
华中师范大学 后端工程师
点赞 评论 收藏
分享
烤点老白薯:他第二句话的潜台词是想让你帮他点个瑞幸或者喜茶啥的
mt对你说过最有启发的一...
点赞 评论 收藏
分享
昨天 14:09
已编辑
北京交通大学 算法工程师
字节跳动 训练框架研发 (N+2) * (12 + 3) 硕士211
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务