結果

問題 No.556 仁義なきサルたち
ユーザー hogeover30hogeover30
提出日時 2017-08-11 23:44:17
言語 C++17
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 20 ms / 2,000 ms
コード長 1,470 bytes
コンパイル時間 2,126 ms
コンパイル使用メモリ 200,784 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-04-20 23:50:22
合計ジャッジ時間 3,039 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;

struct union_find_tree {
    std::vector<int> par, rank;
    union_find_tree(){}
    union_find_tree(int size)
    {
        par=std::vector<int>(size);
        rank=std::vector<int>(size);
        for(int i=0; i<size; ++i) par[i]=i;
    }
    int root(int x)
    {
        if (x==par[x]) return x;
        return par[x]=root(par[x]);
    }
    void unite(int x, int y)
    {
        x=root(x);
        y=root(y);
        if (x==y) return;
        if (rank[x]<rank[y]) {
            par[x]=y;
        }
        else {
            par[y]=x;
            if (rank[x]==rank[y]) ++rank[x];
        }
    }
    bool same(int x, int y)
    {
        return root(x)==root(y);
    }
};

int main()
{
    int n, m; cin>>n>>m;
    union_find_tree t(n);
    vector<int> boss(n), size(n, 1);
    for(int i=0; i<n; ++i) boss[i]=i;

    while (m--) {
        int a, b; cin>>a>>b;
        --a, --b;
        if (t.same(a, b)) continue;
        int bossA=boss[t.root(a)];
        int bossB=boss[t.root(b)];
        t.unite(a, b);
        int win, lose;
        if (size[bossA]==size[bossB]) {
            win=min(bossA, bossB);
            lose=max(bossA, bossB);
        }
        else {
            win=bossA, lose=bossB;
            if (size[bossA]<size[bossB]) swap(win, lose);
        }
        boss[t.root(a)]=win;
        size[win]+=size[lose];
        size[lose]=0;
    }
    for(int i=0; i<n; ++i) cout<<boss[t.root(i)]+1<<endl;
}

0