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;
const int N = 200'007;
int n, k;
vector<int> adj[N];
int c[N];
vector<int> col[N];
int vis[N], sz[N], par[N], done[N], tim;
vector<int> cur[N];
void prepare(int u, int f) {
sz[u] = 1;
cur[c[u]].push_back(u);
for (int v : adj[u]) if (!vis[v] && v != f) {
prepare(v, u);
sz[u] += sz[v];
par[v] = u;
}
}
int find_centroid(int u, int f, int all) {
for (int v : adj[u]) if (!vis[v] && v != f) {
if (sz[v] >= all / 2) {
return find_centroid(v, u, all);
}
}
return u;
}
void clear(int u, int f) {
cur[c[u]].clear();
for (int v : adj[u]) if (!vis[v] && v != f) {
clear(v, u);
}
}
int ans = N;
void solve(int u) {
prepare(u, u);
int centroid = find_centroid(u, u, sz[u]);
clear(u, u);
prepare(centroid, centroid);
queue<int> q;
q.push(c[centroid]);
++tim;
done[c[centroid]] = tim;
int now = 0;
while (q.size()) {
int v = q.front(); q.pop();
now++;
if (cur[v].size() != col[v].size()) {
now = N;
break;
}
for (int w : cur[v]) if (w != centroid) {
w = par[w];
if (done[c[w]] != tim) {
done[c[w]] = tim;
q.push(c[w]);
}
}
}
ans = min(ans, now - 1);
clear(centroid, centroid);
vis[centroid] = true;
for (int v : adj[centroid]) if (!vis[v]) {
solve(v);
}
}
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
cin >> n >> k;
for (int i = 0; i < n - 1; i++) {
int u, v; cin >> u >> v; u--, v--;
adj[u].push_back(v);
adj[v].push_back(u);
}
for (int i = 0; i < n; i++) {
cin >> c[i]; c[i]--;
col[c[i]].push_back(i);
}
solve(0);
cout << ans << '\n';
}
# | 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... |