結果

問題 No.2290 UnUnion Find
ユーザー ynm3n
提出日時 2023-05-05 23:56:26
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
WA  
実行時間 -
コード長 1,771 bytes
コンパイル時間 894 ms
コンパイル使用メモリ 89,460 KB
最終ジャッジ日時 2025-02-12 20:14:00
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample WA * 1
other AC * 18 WA * 28
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <map>
using namespace std;

class UnionFindTree {
public:
    vector<int> parent;
    int cnt;
    map<int, bool> roots;

    UnionFindTree(int n) {
        parent.resize(n, -1);
        cnt = n;
        for (int i = 0; i < n; i++) {
            roots.insert(make_pair(i, true));
        }
    }

    int findRoot(int a) {
        if (parent[a] < 0) {
            return a;
        }
        int r = findRoot(parent[a]);
        if (roots.count(a) != 0 && a != r) {
            roots.erase(a);
        }
        parent[a] = r;
        return r;
    }

    bool unite(int a, int b) {
        int x = findRoot(a), y = findRoot(b);
        if (x == y) {
            return false;
        }
        if (size(x) < size(y)) {
            swap(x, y);
        }
        roots.erase(y);
        parent[x] += parent[y];
        parent[y] = x;
        cnt--;
        return true;
    }

    bool sameRoot(int a, int b) {
        return findRoot(a) == findRoot(b);
    }

    int size(int a) {
        return -parent[findRoot(a)];
    }
};

int main() {
    int n, q;
    cin >> n >> q;

    UnionFindTree uf(n);
    int typ, u, v;
    for (int i = 0; i < q; i++) {
        cin >> typ;
        switch (typ) {
        case 1:
            cin >> u >> v;
            u--;
            v--;
            uf.unite(u, v);
            break;
        case 2:
            cin >> v;
            int r = uf.findRoot(v);
            int ans = -1;
            for (auto itr = uf.roots.begin(); itr != uf.roots.end(); itr++) {
                if (r != itr->first) {
                    ans = itr->first + 1;
                    break;
                }
            }
            cout << ans << endl;
            break;
        }
    }

    return 0;
}
0