#include <bits/stdc++.h>
using namespace std;
int a, b;
vector<int> z[1000005];
int low[1000005], high[1000005], col[1000005], res[1000005];
vector<int> st;
int u = 0, v = 0, cur;
int best1_[1000005], best2_[1000005], best3_[1000005];
void dfs(int i, int par) {
low[i] = 1;
for (int p : z[i]) if (p != par) {
high[p] = high[i] + 1;
dfs(p, i);
low[i] = max(low[i], low[p] + 1);
}
}
void prepare_top3(int n) {
for (int i = 1; i <= n; i++) {
int v1 = 0, v2 = 0, v3 = 0, id1 = 0, id2 = 0, id3 = 0;
for (int p : z[i]) {
int L = low[p];
if (L > v1) {
v3 = v2; id3 = id2;
v2 = v1; id2 = id1;
v1 = L; id1 = p;
} else if (L > v2) {
v3 = v2; id3 = id2;
v2 = L; id2 = p;
} else if (L > v3) {
v3 = L; id3 = p;
}
}
best1_[i] = id1;
best2_[i] = id2;
best3_[i] = id3;
}
}
void dfs1(int i, int par) {
if (i != cur && z[i].size() == 1) {
res[i] = max(res[i], (int)st.size());
return;
}
int heavy = (best1_[i] != par ? best1_[i] : best2_[i]);
int nextb = (best1_[i] != par ? best2_[i] : best3_[i]);
if (nextb) {
while (!st.empty() && high[i] - high[st.back()] <= low[nextb]) {
st.pop_back();
}
}
st.push_back(i);
if (heavy) dfs1(heavy, i);
if (heavy) {
while (!st.empty() && high[i] - high[st.back()] <= low[heavy]) {
st.pop_back();
}
}
res[i] = max(res[i], (int)st.size());
for (int p : z[i]) if (p != par && p != heavy) {
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);
prepare_top3(a);
dfs1(u, 0);
st.clear();
cur = v;
memset(high, 0, sizeof high);
dfs(v, 0);
prepare_top3(a);
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 time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |