結果

問題 No.556 仁義なきサルたち
ユーザー Manuel1024Manuel1024
提出日時 2021-05-06 11:07:45
言語 C++14
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 20 ms / 2,000 ms
コード長 1,227 bytes
コンパイル時間 820 ms
コンパイル使用メモリ 75,100 KB
実行使用メモリ 4,352 KB
最終ジャッジ日時 2023-10-12 04:18:17
合計ジャッジ時間 2,380 ms
ジャッジサーバーID
(参考情報)
judge12 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,348 KB
testcase_01 AC 1 ms
4,348 KB
testcase_02 AC 1 ms
4,348 KB
testcase_03 AC 1 ms
4,352 KB
testcase_04 AC 2 ms
4,348 KB
testcase_05 AC 2 ms
4,348 KB
testcase_06 AC 2 ms
4,348 KB
testcase_07 AC 2 ms
4,348 KB
testcase_08 AC 2 ms
4,348 KB
testcase_09 AC 3 ms
4,352 KB
testcase_10 AC 3 ms
4,348 KB
testcase_11 AC 3 ms
4,352 KB
testcase_12 AC 3 ms
4,352 KB
testcase_13 AC 8 ms
4,348 KB
testcase_14 AC 9 ms
4,348 KB
testcase_15 AC 10 ms
4,352 KB
testcase_16 AC 16 ms
4,348 KB
testcase_17 AC 17 ms
4,348 KB
testcase_18 AC 20 ms
4,348 KB
testcase_19 AC 18 ms
4,352 KB
testcase_20 AC 19 ms
4,348 KB
testcase_21 AC 19 ms
4,348 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct UnionFind{
    vector<int> parent;
    UnionFind(int n){
        parent = vector<int>(n, -1);
    }

    int root(int x){
        if(parent[x] < 0) return x;
        else return parent[x] = root(parent[x]);
    }

    int count(int x){
        return -parent[root(x)];
    }

    bool same(int x, int y){
        return root(x) == root(y);
    }

    void unite(int winner, int loser){
        winner = root(winner);
        loser = root(loser);
        parent[winner] += parent[loser];
        parent[loser] = winner;
    }
};

int main(){
    int n, m;
    cin >> n >> m;
    UnionFind data(n);
    auto winner = [&](int x, int y){
        if(data.count(x) == data.count(y)) return min(x, y);
        else if(data.count(x) > data.count(y)) return x;
        else return y;
    };
    for(int i = 0; i < m; i++){
        int a, b;
        cin >> a >> b;
        a--; b--;
        a = data.root(a);
        b = data.root(b);
        if(data.same(a, b)) continue;

        int w = winner(a, b);
        int l = (w == a) ? b : a;
        data.unite(w, l);
    }

    for(int i = 0; i < n; i++) cout << data.root(i)+1 << endl;
    return 0;
}
0