結果

問題 No.1390 Get together
ユーザー cutmdocutmdo
提出日時 2022-09-04 13:21:24
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 287 ms / 2,000 ms
コード長 1,578 bytes
コンパイル時間 826 ms
コンパイル使用メモリ 85,428 KB
実行使用メモリ 141,568 KB
最終ジャッジ日時 2024-04-29 13:16:50
合計ジャッジ時間 6,867 ms
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
5,248 KB
testcase_01 AC 1 ms
5,376 KB
testcase_02 AC 2 ms
5,376 KB
testcase_03 AC 6 ms
6,016 KB
testcase_04 AC 5 ms
5,640 KB
testcase_05 AC 5 ms
6,144 KB
testcase_06 AC 5 ms
5,504 KB
testcase_07 AC 6 ms
5,504 KB
testcase_08 AC 5 ms
5,604 KB
testcase_09 AC 6 ms
6,400 KB
testcase_10 AC 2 ms
5,376 KB
testcase_11 AC 2 ms
5,376 KB
testcase_12 AC 2 ms
5,376 KB
testcase_13 AC 2 ms
5,376 KB
testcase_14 AC 1 ms
5,376 KB
testcase_15 AC 2 ms
5,376 KB
testcase_16 AC 221 ms
141,532 KB
testcase_17 AC 280 ms
139,912 KB
testcase_18 AC 246 ms
141,568 KB
testcase_19 AC 276 ms
139,904 KB
testcase_20 AC 281 ms
139,904 KB
testcase_21 AC 282 ms
139,904 KB
testcase_22 AC 259 ms
140,800 KB
testcase_23 AC 270 ms
140,728 KB
testcase_24 AC 277 ms
140,800 KB
testcase_25 AC 287 ms
139,904 KB
testcase_26 AC 285 ms
139,992 KB
testcase_27 AC 287 ms
139,904 KB
testcase_28 AC 284 ms
139,884 KB
testcase_29 AC 286 ms
139,904 KB
testcase_30 AC 285 ms
139,904 KB
testcase_31 AC 284 ms
139,948 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <deque>
#include <numeric>

class UnionFind {
    std::vector<int> m_root;
    std::vector<int> m_depth;
    std::vector<int> m_size;
public:
    UnionFind(int size) :
        m_root(size),
        m_depth(size, 0),
        m_size(size, 1) {
        std::iota(m_root.begin(), m_root.end(), 0);
    }
    void unite(int x, int y) {
        x = root(x); y = root(y);
        if(x == y) { return; }
        auto t = size(x) + size(y);
        m_size[x] = m_size[y] = t;
        if(m_depth[x] < m_depth[y]) { m_root[x] = y; } else { m_root[y] = x; }
        if(m_depth[x] == m_depth[y]) { ++m_depth[x]; }
    }
    bool isSame(int x, int y) {
        return root(x) == root(y);
    }
    int root(int x) {
        if(m_root[x] == x) { return x; }
        return m_root[x] = root(m_root[x]);
    }
    int size(int x) {
        if(m_root[x] == x) { return m_size[x]; }
        return size(m_root[x] = root(m_root[x]));
    }
};

using ll = long long;
using std::cout;
using std::cin;
constexpr char endl = '\n';

signed main() {
    ll n, m;
    cin >> n >> m;
    std::vector<std::deque<ll>> cv(n);
    for(int _ = 0; _ < n; ++_) {
        ll b, c;
        cin >> b >> c;
        cv[c - 1].emplace_back(b - 1);
    }

    auto dsu = UnionFind(m);

    ll ans = 0;
    for(const auto& dq : cv) if(!dq.empty()) {
        auto base = dq.front();
        for(const auto& tg : dq) {
            if(!dsu.isSame(base, tg)) {
                dsu.unite(base, tg);
                ++ans;
            }
        }
    }
    cout << ans << endl;
}
0