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>
using namespace std;
using ll = long long;
#define all(x) (x).begin(), (x).end()
const int N = 2007, L = 13;
int n, k;
vector<int> adj[N], col[N], g[N], rev[N], topo, comp;
int c[N], lift[N][L], dep[N], head[N];
bool vis[N];
void dfs(int v = 1, int p = 0) {
lift[v][0] = p;
for (int i = 1; i < L; i++)
lift[v][i] = lift[lift[v][i - 1]][i - 1];
for (int u : adj[v]) {
if (u != p) {
dep[u] = dep[v] + 1;
dfs(u, v);
}
}
}
void dfs1(int v) {
vis[v] = 1;
for (int u : g[v])
if (!vis[u])
dfs1(u);
topo.push_back(v);
}
void dfs2(int v) {
vis[v] = 1;
comp.push_back(v);
for (int u : rev[v])
if (!vis[u])
dfs2(u);
}
int lca(int u, int v) {
if (dep[u] > dep[v])
swap(u, v);
for (int i = L - 1; ~i; --i)
if (dep[v] - (1 << i) >= dep[u])
v = lift[v][i];
if (u == v)
return u;
for (int i = L - 1; ~i; --i)
if (lift[v][i] != lift[u][i])
v = lift[v][i], u = lift[u][i];
return lift[u][0];
}
int main() {
cin.tie(0)->sync_with_stdio(false);
cin >> n >> k;
for (int i = 1; i < n; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
for (int i = 1; i <= n; i++) {
cin >> c[i];
col[c[i]].push_back(i);
}
dfs();
for (int i = 1; i <= k; i++) {
int l = col[i][0];
for (int v : col[i])
l = lca(l, v);
g[i].push_back(c[l]);
for (int v : col[i]) {
while (v != l) {
g[i].push_back(c[v]);
v = lift[v][0];
}
}
sort(all(g[i]));
g[i].erase(unique(all(g[i])), g[i].end());
for (int u : g[i])
rev[u].push_back(i);
}
for (int i = 1; i <= k; i++)
if (!vis[i])
dfs1(i);
reverse(all(topo));
memset(vis, 0, sizeof(vis));
int ans = k - 1;
for (int v : topo) {
if (!vis[v]) {
comp.clear();
dfs2(v);
for (int x : comp)
head[x] = comp.front();
bool out = 0;
for (int x : comp) {
for (int u : g[x]) {
if (head[u] != head[x])
out = 1;
}
}
if (!out)
ans = min(ans, (int) comp.size() - 1);
}
}
cout << ans << '\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... |