結果

問題 No.556 仁義なきサルたち
ユーザー okchan08okchan08
提出日時 2018-04-05 22:09:51
言語 C++11
(gcc 11.4.0)
結果
WA  
実行時間 -
コード長 1,509 bytes
コンパイル時間 500 ms
コンパイル使用メモリ 62,680 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-08 17:51:17
合計ジャッジ時間 2,072 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <iostream>
#include <vector>

using namespace std;

class UnionFind{
    public:
        UnionFind(){
            UnionFind(0);
        }

        UnionFind(int N){
            par.resize(N);
            rnk.resize(N);
            for(int i=0;i<N;i++){
                par[i] = i;
                rnk[i] = 1;
            }
        }

        int root(int x){
            return par[x] = par[x] == x ? x : root(par[x]);
        }

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

        void unite(int x, int y){
            x = root(x); y = root(y);
            if(x == y) return;
            if(rnk[x] < rnk[y]){
                par[x] = y;
                rnk[y] += rnk[x];
            }else if(rnk[y] < rnk[x]){
                par[y] = x;
                rnk[x] += rnk[y];
            }else if(rnk[x] == rnk[y]){
                if(x < y){
                    par[y] = x;
                    rnk[x]++;
                }else{
                    par[x] = y;
                    rnk[y]++;
                }
            }
        }

        int getrnk(int i){
            return rnk[i];
        }

    private:
        vector<int> par, rnk;
};

int main(){
    int N; cin >> N;
    UnionFind uf = UnionFind(N);

    int M; cin >> M;
    int A,B;
    for(int i=0;i<M;i++){
        cin >> A >> B;
        A--; B--;
        if(uf.same(A,B)) continue;
        uf.unite(A,B);
    }
    for(int i=0;i<N;i++){
        cout << uf.root(i) + 1 << endl;
    }
    return 0;
}
0