이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#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... |