Submission #1225497

#TimeUsernameProblemLanguageResultExecution timeMemory
1225497minhpkUnique Cities (JOI19_ho_t5)C++20
0 / 100
2096 ms34692 KiB
#include <bits/stdc++.h>
using namespace std;

int a, b;
vector<int> z[1000005];
int low[1000005];
int high[1000005];
int col[1000005];
int res[1000005];
vector<int> st;
int u = 0, v = 0, cur;

void dfs(int i, int par) {
    low[i] = 1;
    for (int p : z[i]) {
        if (p == par) continue;
        high[p] = high[i] + 1;
        dfs(p, i);
        low[i] = max(low[i], low[p] + 1);
    }
}

bool cmp_low(int A, int B) {
    return low[A] > low[B];
}

void dfs1(int i, int par) {
    if (i != cur && z[i].size() == 1) {
        res[i] = max(res[i], (int)st.size());
        return;
    }

    int sta = (par != 0 ? 1 : 0);

    while ((int)z[i].size() > sta + 1
           && !st.empty()
           && high[i] - high[st.back()] <= low[z[i][sta+1]]) {
        st.pop_back();
    }

    st.push_back(i);
    dfs1(z[i][sta], i);

    while (!st.empty()
           && high[i] - high[st.back()] <= low[z[i][sta]]) {
        st.pop_back();
    }

    res[i] = max(res[i], (int)st.size());

    for (int p : z[i]) {
        if (p == par) continue;
        while (!st.empty() && high[st.back()] >= high[i]) {
            st.pop_back();
        }
        st.push_back(i);
        dfs1(p, i);
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    cin >> a >> b;
    for (int i = 1; i < a; i++) {
        int x, y;
        cin >> x >> y;
        z[x].push_back(y);
        z[y].push_back(x);
    }
    for (int i = 1; i <= a; i++) {
        cin >> col[i];
    }

    dfs(1, 0);
    for (int i = 1; i <= a; i++) {
        if (high[i] > high[u]) u = i;
    }

    memset(high, 0, sizeof high);
    dfs(u, 0);
    for (int i = 1; i <= a; i++) {
        if (high[i] > high[v]) v = i;
    }

    cur = u;
    memset(high, 0, sizeof high);
    dfs(u, 0);
    for (int i = 1; i <= a; i++) {
        sort(z[i].begin(), z[i].end(), cmp_low);
    }
    dfs1(u, 0);

    st.clear();
    cur = v;
    memset(high, 0, sizeof high);
    dfs(v, 0);
    for (int i = 1; i <= a; i++) {
        sort(z[i].begin(), z[i].end(), cmp_low);
    }
    dfs1(v, 0);

    for (int i = 1; i <= a; i++) {
        if (b == 1) {
            cout << (res[i] ? 1 : 0) << "\n";
        } else {
            cout << res[i] << "\n";
        }
    }
    return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...