結果

問題 No.416 旅行会社
ユーザー finefine
提出日時 2016-08-26 23:20:11
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
TLE  
実行時間 -
コード長 2,287 bytes
コンパイル時間 1,938 ms
コンパイル使用メモリ 174,472 KB
実行使用メモリ 19,248 KB
最終ジャッジ日時 2024-04-25 21:48:49
合計ジャッジ時間 12,580 ms
ジャッジサーバーID
(参考情報)
judge4 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 TLE -
testcase_01 -- -
testcase_02 -- -
testcase_03 -- -
testcase_04 -- -
testcase_05 -- -
testcase_06 -- -
testcase_07 -- -
testcase_08 -- -
testcase_09 -- -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
testcase_20 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;

typedef pair<int, int> P;

struct Union_Find {
    //各要素が属する集合の代表(根)を管理する
    //もし、要素xが根であればdata[x]は負の値を取り、-data[x]はxが属する集合の大きさに等しい
    vector<int> data;
    
    Union_Find(int size) : data(size, -1) {}
    bool Union(int x, int y) {
        x = Find(x);
        y = Find(y);
        bool is_union = (x != y);
        if (is_union) {
            if (data[x] > data[y]) swap(x, y);
            data[x] += data[y];
            data[y] = x;
        }
        return is_union;
    }
    int Find(int x) {
        if (data[x] < 0) { //要素xが根である
            return x;
        } else {
            data[x] = Find(data[x]); //data[x]がxの属する集合の根でない場合、根になるよう更新される
            return data[x];
        }
    }
    bool same(int x, int y) {
        return Find(x) == Find(y);
    }
    int size(int x) {
        return -data[Find(x)];
    }
};

void setter(vector<int>& ans, int z, int v, int n, Union_Find& uf) {
    for (int i = 1; i < n; i++) {
        if (uf.same(i, z)) ans[i] = v;
    }
}

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int n, m, q;
    cin >> n >> m >> q;
    vector<P> e;
    for (int i = 0; i < m; i++) {
        int a, b;
        cin >> a >> b;
        a--;
        b--;
        e.emplace_back(a, b);
    }
    vector<P> query;
    for (int i = 0; i < q; i++) {
        int c, d;
        cin >> c >> d;
        c--;
        d--;
        query.emplace_back(c, d);
        e.erase(find(e.begin(), e.end(), P(c, d)));
    }
    Union_Find uf(n);
    for (auto i = e.begin(), f = e.end(); i != f; ++i) {
        uf.Union((*i).first, (*i).second);
    }
    
    vector<int> ans(n, -1);
    for (int i = 1; i < n; i++) {
        if (!uf.same(0, i)) ans[i] = 0;
    }
    
    for (int i = q - 1; i >= 0; i--) {
        int x = query[i].first, y = query[i].second;
        if (uf.same(x, y)) continue;
        if (uf.same(0, x)) setter(ans, y, i + 1, n, uf);
        else if (uf.same(0, y)) setter(ans, x, i + 1, n, uf);
        uf.Union(x, y);
    }
    
    for (int i = 1; i < n; i++) {
        cout << ans[i] << "\n";
    }
    return 0;
}
0