#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int N, K;
cin >> N >> K;
vector<pair<int, int>> edges;
vector<vector<int>> adj(N);
for (int i = 0; i < N - 1; i++) {
int u, v;
cin >> u >> v;
u--, v--;
adj[u].emplace_back(v);
adj[v].emplace_back(u);
edges.emplace_back(u, v);
}
vector<int> color(N);
vector<vector<int>> colorList(K);
for (int i = 0; i < N; i++) {
cin >> color[i];
colorList[--color[i]].emplace_back(i);
}
vector<int> sz(N, 0);
vector<int> par(N, -1);
vector<bool> visColor(K, false);
vector<int> group(N, -1);
function<void(int)> Dfs = [&](int n) {
sz[n] = 1;
for (auto i : adj[n]) if (i != par[n] && group[i] == -1) {
par[i] = n;
Dfs(i);
sz[n] += sz[i];
}
};
auto Centroid = [&](int r) {
par[r] = -1;
Dfs(r);
int Size = sz[r];
while (true) {
pair<int, int> mx = {-1, -1};
for (auto i : adj[r]) if (i != par[r] && group[i] == -1) {
mx = max(mx, {sz[i], i});
}
if (mx.first * 2 <= Size) {
return r;
}
r = mx.second;
}
};
auto Solve = [&](int r) {
int name = r;
vector<int> comp;
par[r] = -1;
Dfs(r);
queue<int> q;
visColor[color[r]] = true;
for (auto i : colorList[color[r]]) {
q.emplace(i);
}
while (!q.empty()) {
int p = par[q.front()];
comp.emplace_back(q.front());
q.pop();
if (p != -1 && !visColor[color[p]]) {
visColor[color[p]] = true;
for (auto i : colorList[color[p]]) {
q.emplace(i);
}
}
}
for (auto i : comp) {
group[i] = name;
}
};
auto CentroidDecomposition = [&]() {
for (int i = 0; i < N; i++) {
while (group[i] == -1) {
Solve(Centroid(i));
}
}
};
CentroidDecomposition();
vector<int> degree(N, 0);
for (int i = 0; i < N - 1; i++) {
int u, v;
tie(u, v) = edges[i];
if (group[u] != group[v]) {
degree[group[u]]++;
degree[group[v]]++;
}
}
int ans = 0;
for (int i = 0; i < N; i++) {
if (group[i] == i && degree[i] <= 1) {
ans++;
}
}
cout << (ans - 1) << "\n";
return 0;
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
5 ms |
384 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
5 ms |
384 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
5 ms |
384 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
57 ms |
9576 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
5 ms |
384 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |