結果

問題 No.1390 Get together
ユーザー srjywrdnprktsrjywrdnprkt
提出日時 2023-06-21 22:48:53
言語 C++17(gcc12)
(gcc 12.3.0 + boost 1.87.0)
結果
AC  
実行時間 176 ms / 2,000 ms
コード長 1,358 bytes
コンパイル時間 2,199 ms
コンパイル使用メモリ 206,060 KB
実行使用メモリ 13,520 KB
最終ジャッジ日時 2024-06-29 07:48:52
合計ジャッジ時間 7,223 ms
ジャッジサーバーID
(参考情報)
judge2 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 29
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;
using ll = long long;

struct UnionFind {
    int ngroup;
    vector<int> par;
    vector<int> siz;

    UnionFind(int N) : par(N), siz(N) {
        ngroup = N;
        for(int i = 0; i < N; i++){
            par[i] = i;
            siz[i] = 1;
        }
    }

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

    int unite(int x, int y) {
        int rx = root(x);
        int ry = root(y);
        if (rx == ry) return rx;
        ngroup--;
        if (siz[rx] > siz[ry]) swap(rx, ry);
        par[rx] = ry;
        siz[ry] += siz[rx];
        return ry;
    }

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

    int size(int x){
        return siz[root(x)];
    }

    int group_count(){
        return ngroup;
    }
};

int main(){
 
    int N, M, c, b, ans=0;
    cin >> N >> M;
    UnionFind tree(M+1);
    vector<vector<int>> color(N+1);
    for (int i=0; i<N; i++){
        cin >> b >> c;
        color[c].push_back(b);
    }

    for (int i=1; i<=N; i++){
        for (int j=0; j<color[i].size(); j++) tree.unite(color[i][0], color[i][j]);
    }

    for (int i=1; i<=M; i++){
        if (tree.root(i) == i) ans += tree.size(i)-1;
    }

    cout << ans << endl;
 
    return 0;
}
0