結果

問題 No.556 仁義なきサルたち
ユーザー dnishdnish
提出日時 2018-06-22 02:10:41
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 21 ms / 2,000 ms
コード長 1,978 bytes
コンパイル時間 1,621 ms
コンパイル使用メモリ 173,344 KB
実行使用メモリ 4,384 KB
最終ジャッジ日時 2023-09-13 07:49:00
合計ジャッジ時間 2,721 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include "bits/stdc++.h"
#define REP(i,n,N) for(ll i=(n); i<(N); i++)
#define RREP(i,n,N) for(ll i=(N-1); i>=n; i--)
#define CK(n,a,b) ((a)<=(n)&&(n)<(b))
#define ALL(v) (v).begin(),(v).end()
#define p(s) cout<<(s)<<endl
#define p2(a,b) cout<<(a)<<" "<<(b)<<endl
#define v2(T) vector<vector<T>>
typedef long long ll;
using namespace std;
const ll mod = 1e9+7;


struct UnionFind_QFW {
    vector<int> i2g;  // i2g[i]:アイテムiの所属するグループの番号
    /* アイテムの種類を変えたいときは下を変更 */
    vector<vector<int>> g2i; // g2i[g]:グループgに所属するアイテムたち

    UnionFind_QFW(int n) {
        i2g.resize(n);
        g2i.resize(n);
        for (int i = 0; i < n; i++) {
            i2g[i] = i;
            g2i[i].assign(1, i); // アイテムiを1つ割り当てる
        }
    }

    // 同じグループに所属しているか
    bool same(int ix, int iy) {
        return i2g[ix] == i2g[iy];
    }

    // xの所属するグループとyの所属するグループを結合
    void merge(int ix, int iy) {
        if (same(ix, iy)) return; // 同じグループなら何もしない

        // グループxのアイテム数 > グループyのアイテム数  となるように(※ 一般的なマージテク)
        if (g2i[i2g[ix]].size() < g2i[i2g[iy]].size() || (g2i[i2g[ix]].size() == g2i[i2g[iy]].size() && i2g[ix] > i2g[iy])) {
            swap(ix, iy);
        }

        // gxの要素数 > gyの要素数
        int gx = i2g[ix];
        int gy = i2g[iy];
        for (int j : g2i[gy]) {
            i2g[j] = gx;
        }

        g2i[gx].insert(g2i[gx].end(), g2i[gy].begin(), g2i[gy].end()); // グループの結合
        g2i[gy].clear();
    }
};

int main() {
    int N,M;
    cin>>N>>M;
    UnionFind_QFW uf(N);
    REP(i,0,M){
        int a,b;
        cin>>a>>b;
        a--;b--;
        if(!uf.same(a,b)) uf.merge(a, b);

    }
    REP(i,0,N){
        p(uf.i2g[i]+1);
    }
}
0