結果

問題 No.3189 Semifinal Stage
ユーザー jiangxinyang
提出日時 2025-06-20 22:52:35
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 650 ms / 4,000 ms
コード長 2,088 bytes
コンパイル時間 2,023 ms
コンパイル使用メモリ 203,128 KB
実行使用メモリ 69,216 KB
最終ジャッジ日時 2025-06-20 22:52:55
合計ジャッジ時間 16,050 ms
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 30
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
using pii = pair<int, int>;
const int MAXN = 200000;

int N, Q;
vector<int> adj[MAXN + 1];
bool used[MAXN + 1];
int sub_sz[MAXN + 1];
vector<pii> vv[MAXN + 1];
multiset<int> ms[MAXN + 1];
bool color[MAXN + 1];
int dfs_sz(int u, int p) {
    sub_sz[u] = 1;
    for (int v : adj[u]) {
        if (v != p && !used[v]) sub_sz[u] += dfs_sz(v, u);
    }
    return sub_sz[u];
}

int dfs2(int u, int p, int total) {
    for (int v : adj[u]) {
        if (v != p && !used[v]) {
            if (sub_sz[v] > total / 2) return dfs2(v, u, total);
        }
    }
    return u;
}

void dfs_dist(int u, int p, int d, int c) {
    vv[u].emplace_back(c, d);
    for (int v : adj[u])
        if (v != p && !used[v]) dfs_dist(v, u, d + 1, c);
}

void build_cd(int root = 1, int parent = 0) {
    int total = dfs_sz(root, 0);
    int c = dfs2(root, 0, total);
    used[c] = true;
    dfs_dist(c, 0, 0, c);
    for (int v : adj[c]) {
        if (!used[v]) build_cd(v, c);
    }
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cin >> N;
    for (int i = 1; i < N; i++) {
        int u, v;
        cin >> u >> v;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }

    build_cd();

    cin >> Q;
    while (Q--) {
        int type, v;
        cin >> type >> v;
        if (type == 1) {
            color[v] = !color[v];
            if (color[v]) {
                for (auto &pr : vv[v]) {
                    int c = pr.first, d = pr.second;
                    ms[c].insert(d);
                }
            } else {
                for (auto &pr : vv[v]) {
                    int c = pr.first, d = pr.second;
                    auto it = ms[c].find(d);
                    if (it != ms[c].end()) ms[c].erase(it);
                }
            }
        } else {
            int ans = INT_MAX;
            for (auto &pr : vv[v]) {
                int c = pr.first, d = pr.second;
                if (!ms[c].empty()) ans = min(ans, *ms[c].begin() + d);
            }
            cout << ans << "\n";
        }
    }
    return 0;
}
0