题解 | #第一题#

第一题

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

并查集

#include <iostream>
#include <vector>
using namespace std;
const int MAXN=1000010;

vector<int> s(MAXN, -1);
vector<bool> visited(MAXN, false);

int Find(vector<int>& s, int x) {
    int root = x;
    while (s[root] >= 0) {
        root = s[root];
    }
    while (x != root) {
        int t = s[x];
        s[x] = root;
        x = t;
    }
    return root;
}

void Union(vector<int>& s, int a, int b) {
    int roota = Find(s, a);
    int rootb = Find(s, b);
    if (roota == rootb) return;
    if (s[roota] <= s[rootb]) {
        s[roota] += s[rootb];
        s[rootb] = roota;
    }
    else {
        s[rootb] += s[roota];
        s[roota] = rootb;
    }
}

int main()
{
    int a, b;
    while (cin >> a >> b) {
        Union(s, a, b);
        visited[a] = true;
        visited[b] = true;
    }
    int component = 0;
    for (int i = 0; i < MAXN; i++) {
        if (!visited[i]) continue;
        if (s[i] <= 0) component++;
    }
    cout << component << endl;
    return 0;
}
全部评论

相关推荐

明天不下雨了_人机版:让我们大声的说出来:以前的未来就是现在
点赞 评论 收藏
分享
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-30 18:19
个个985的硕士闭着眼睛都有15k以上的月薪,天天嚷嚷着研究生白度读了,天天嚷嚷着反向读研了........
MMMJC:不读研22本科出去的基本都拿28k呢,你不能用25的研究生和25的本科生比然后说没反向读研,而是25研和22本比呀
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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