結果

問題 No.556 仁義なきサルたち
ユーザー tottoripapertottoripaper
提出日時 2017-08-14 13:24:55
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 17 ms / 2,000 ms
コード長 1,829 bytes
コンパイル時間 1,602 ms
コンパイル使用メモリ 164,480 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-04-21 11:20:57
合計ジャッジ時間 2,600 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
5,248 KB
testcase_01 AC 2 ms
5,376 KB
testcase_02 AC 2 ms
5,376 KB
testcase_03 AC 2 ms
5,376 KB
testcase_04 AC 2 ms
5,376 KB
testcase_05 AC 3 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 16 ms
5,376 KB
testcase_18 AC 17 ms
5,376 KB
testcase_19 AC 16 ms
5,376 KB
testcase_20 AC 17 ms
5,376 KB
testcase_21 AC 17 ms
5,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;

#define fst(t) std::get<0>(t)
#define snd(t) std::get<1>(t)
#define thd(t) std::get<2>(t)
#define unless(p) if(!(p))
#define until(p) while(!(p))

using ll = long long;
using P = std::tuple<int,int>;

const int dx[8] = {-1, 1, 0, 0, -1, -1, 1, 1}, dy[8] = {0, 0, -1, 1, -1, 1, -1, 1};

template <int n>
struct UnionFind{
    UnionFind(){
        for(int i=0;i<n;i++){
            par[i] = i;
            rank[i] = 0;
            cnt[i] = 1;
            boss[i] = i;
        }
    }
    int find(int x){
        if(x == par[x])return x;
        return par[x] = find(par[x]);
    }
    bool same(int x, int y){
        return find(x) == find(y);
    }
    void unite(int x, int y, int b){
        x = find(x);
        y = find(y);
        if(x == y){return;}
        
        if(rank[x] > rank[y]){
            par[y] = x;
            cnt[x] += cnt[y];
            boss[x] = b;
        }else{
            par[x] = y;
            cnt[y] += cnt[x];
            boss[y] = b;
            if(rank[x] == rank[y]){rank[y]++;}
        }
    }
    int rank[n], par[n], cnt[n], boss[n];
};

UnionFind<10100> uf;
int N, M;

int main(){
    std::cin.tie(nullptr);
    std::ios::sync_with_stdio(false);

    std::cin >> N >> M;

    for(int i=0;i<M;++i){
        int a, b;
        std::cin >> a >> b;

        int pa = uf.find(a), pb = uf.find(b);
        if(uf.cnt[pa] > uf.cnt[pb] ||
           (uf.cnt[pa] == uf.cnt[pb] && uf.boss[pa] < uf.boss[pb])){
            uf.unite(pa, pb, uf.boss[pa]);
        }else{
            uf.unite(pa, pb, uf.boss[pb]);
        }

        // for(int j=1;j<=N;++j){
        //     std::cout << uf.boss[uf.find(j)] << " \n"[j == N];
        // }
    }

    for(int i=1;i<=N;++i){
        int b = uf.boss[uf.find(i)];
        std::cout << b << std::endl;
    }
}
0