結果

問題 No.2563 色ごとのグループ
ユーザー int_sanint_san
提出日時 2023-12-02 15:30:33
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 217 ms / 2,000 ms
コード長 1,326 bytes
コンパイル時間 1,992 ms
コンパイル使用メモリ 180,064 KB
実行使用メモリ 25,212 KB
最終ジャッジ日時 2023-12-02 15:30:40
合計ジャッジ時間 6,117 ms
ジャッジサーバーID
(参考情報)
judge14 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
6,676 KB
testcase_01 AC 2 ms
6,676 KB
testcase_02 AC 1 ms
6,676 KB
testcase_03 AC 1 ms
6,676 KB
testcase_04 AC 1 ms
6,676 KB
testcase_05 AC 2 ms
6,676 KB
testcase_06 AC 1 ms
6,676 KB
testcase_07 AC 2 ms
6,676 KB
testcase_08 AC 1 ms
6,676 KB
testcase_09 AC 1 ms
6,676 KB
testcase_10 AC 2 ms
6,676 KB
testcase_11 AC 2 ms
6,676 KB
testcase_12 AC 2 ms
6,676 KB
testcase_13 AC 2 ms
6,676 KB
testcase_14 AC 2 ms
6,676 KB
testcase_15 AC 2 ms
6,676 KB
testcase_16 AC 3 ms
6,676 KB
testcase_17 AC 3 ms
6,676 KB
testcase_18 AC 2 ms
6,676 KB
testcase_19 AC 5 ms
6,676 KB
testcase_20 AC 14 ms
6,676 KB
testcase_21 AC 9 ms
6,676 KB
testcase_22 AC 7 ms
6,676 KB
testcase_23 AC 12 ms
6,676 KB
testcase_24 AC 109 ms
11,780 KB
testcase_25 AC 92 ms
13,124 KB
testcase_26 AC 136 ms
18,048 KB
testcase_27 AC 125 ms
24,160 KB
testcase_28 AC 151 ms
19,760 KB
testcase_29 AC 212 ms
25,212 KB
testcase_30 AC 209 ms
25,212 KB
testcase_31 AC 210 ms
25,212 KB
testcase_32 AC 217 ms
25,212 KB
testcase_33 AC 195 ms
18,940 KB
testcase_34 AC 188 ms
18,940 KB
testcase_35 AC 197 ms
18,940 KB
testcase_36 AC 202 ms
18,940 KB
testcase_37 AC 199 ms
18,940 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
struct UnionFind {
    vector<int> parent, rank, siz;
    UnionFind(int n) {
        parent.resize(n, -1);
        rank.resize(n, 1);
        siz.resize(n, 1);
    }
    int find(int x) {
        if (parent[x] == -1) {
            return x;
        } else {
            return parent[x] = find(parent[x]);
        }
    }
    void unite(int x, int y) {
        x = find(x);
        y = find(y);
        if (x == y) {
            return;
        }
        if (rank[x] < rank[y]) {
            swap(x, y);
        }
        parent[y] = x;
        if (rank[x] == rank[y]) {
            rank[x]++;
        }
        siz[x] += siz[y];
    }
    bool same(int x, int y) { return find(x) == find(y); }
    int size(int x) { return siz[find(x)]; }
};
int main() {
    int N, M;
    cin >> N >> M;
    vector<int> C(N);
    for (int i = 0; i < N; i++) {
        cin >> C[i];
        C[i]--;
    }
    UnionFind uf(N);
    for (int i = 0; i < M; i++) {
        int u, v;
        cin >> u >> v;
        u--;
        v--;
        if (C[u] == C[v]) uf.unite(u, v);
    }
    int ans = 0;
    vector<set<int>> g(N);
    for (int i = 0; i < N; i++) {
        g[C[i]].insert(uf.find(i));
    }
    for (auto i : g) {
        if (i.size() > 0) ans += i.size() - 1;
    }
    cout << ans << endl;
}
0