This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#ifdef __LOCAL__
#include <debug_local.h>
#endif
using namespace std;
const int mxN = 5e5 + 5;
const int lg = 20;
vector<int> ad[mxN];
int c[mxN];
int p[mxN][lg];
int d[mxN];
int mn[mxN];
int f[mxN];
int leafs = 0;
int comps = 0;
void dfs(int u) {
for (int i = 1; i < lg; i++) {
p[u][i] = p[p[u][i - 1]][i - 1];
}
for (int v : ad[u]) {
if (v == p[u][0]) continue;
p[v][0] = u;
d[v] = d[u] + 1;
dfs(v);
}
}
int lca(int u, int v) {
if (d[u] < d[v]) swap(u, v);
for (int j = 0; j < lg; j++) {
if ((d[u] - d[v]) & (1 << j)) {
u = p[u][j];
}
}
if (u == v) return u;
for (int i = lg - 1; i >= 0; i--) {
if (p[u][i] != p[v][i]) {
u = p[u][i];
v = p[v][i];
}
}
return p[u][0];
}
void decompose(int u) {
for (int v : ad[u]) {
if (v == p[u][0]) continue;
decompose(v);
mn[u] = min(mn[u], mn[v]);
f[u] += f[v];
}
if (mn[u] == d[u]) {
comps++;
if (f[u] == 0) leafs++;
f[u] = 1;
}
}
void testCase() {
int n, k;
cin >> n >> k;
for (int i = 1; i < n; i++) {
int u, v;
cin >> u >> v;
ad[u].push_back(v);
ad[v].push_back(u);
}
for (int i = 1; i <= n; i++) cin >> c[i];
dfs(1);
{
vector<int> nodes[k + 1];
for (int i = 1; i <= n; i++) {
mn[i] = d[i];
nodes[c[i]].push_back(i);
}
for (int i = 1; i <= k; i++) {
int l = nodes[i][0];
for (int j : nodes[i]) {
l = lca(l, j);
}
for (int j : nodes[i]) {
mn[j] = min(mn[j], d[l]);
}
}
}
decompose(1);
if (comps == 1) leafs--;
cout << (leafs + 1) / 2 << "\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
testCase();
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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |