题解 | #第一题#

第一题

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

并查集简单运用

#include<iostream>
#include<map>
using namespace std;
map<int,int> mp;
int find(int x){
    if(x != mp[x])
        return mp[x] = find(mp[x]);
    return mp[x];
}
int main()
{
    int a,b,cnt = 0;
    while(cin >> a >> b && a && b){
        if(mp.find(a) == mp.end())
            mp[a] = a;
        if(mp.find(b) == mp.end())
            mp[b] = b;
        int c1 = find(a);
        int c2 = find(b);
        if(c1 == c2)continue;
        else
            mp[c1] = c2;
    }
    for(auto it : mp)
        if(it.first == it.second)
            cnt++;
    cout << cnt;
}
全部评论

相关推荐

LemontreeN:有的兄弟有的我今天一天面了五场,4个二面一个hr面
投递字节跳动等公司9个岗位
点赞 评论 收藏
分享
06-12 10:50
门头沟学院 Java
你的不定积分没加C:我怎么在学院群看到了同样的话
点赞 评论 收藏
分享
评论
14
1
分享

创作者周榜

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