题解 | #第一题#

第一题

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

#include <iostream>
#include "map"

#define  N 65535;
using namespace std;
map<int, int> son_TO_Father;
//连通问题直接想到并查集

//找爸爸
int FindFather(int u) {
    if (u == son_TO_Father[u]) {
        return u;
    } else {
        son_TO_Father[u] = FindFather(son_TO_Father[u]);
        return son_TO_Father[u];
    }
}

//合并两个集合
void UnionSet(int u, int v) {
    int u_root = FindFather(u);
    int v_root = FindFather(v);
    if (u_root != v_root) {
        son_TO_Father[v_root] = u_root;
    }
}

//判断连通子图的个数
int CountGraph() {
    int count = 0;
    for (auto it : son_TO_Father) {
        if (it.first == it.second) {
            ++count;
        }
    }
    return count;
}

int main() {
    int a, b;
    while (cin >> a >> b && a && b) {//注意while处理多个case
	  //初始化并查集
        if (son_TO_Father.find(a) == son_TO_Father.end()) {
            son_TO_Father[a] = a;
        }
        if (son_TO_Father.find(b) == son_TO_Father.end()) {
            son_TO_Father[b] = b;
        }
        UnionSet(a, b);
    }
    printf("%d\n", CountGraph());
    return 0;
}

全部评论

相关推荐

09-13 08:41
服装/纺织设计
那一天的Java_J...:你第一次参加面试吗
点赞 评论 收藏
分享
野猪不是猪🐗:😇:恭喜你以出色的表现成为xxx的一员 😨:您以进入本公司人才库 实际点开:您愿望单中的xxx正在特卖!
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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