#include <bits/stdc++.h>
constexpr int inf = 100000000;
int main() {
int N, K;
std::cin >> N >> K;
std::vector<int> A(N - 1), B(N - 1), O(K);
std::vector<std::vector<int>> tree(N);
for (int i = 0; i < N - 1; ++i) {
std::cin >> A[i] >> B[i];
--A[i], --B[i];
tree[A[i]].push_back(B[i]);
tree[B[i]].push_back(A[i]);
}
for (auto &e : O) {
std::cin >> e;
--e;
}
std::queue<int> que;
std::vector<int> dist(N, -1);
for (const int e : O) {
que.push(e);
dist[e] = 0;
}
while (not que.empty()) {
const int f = que.front();
que.pop();
for (const int t : tree[f]) {
if (dist[t] == -1) {
dist[t] = dist[f] + 1;
que.push(t);
}
}
}
std::vector<int> depth(N), ac(N);
auto dfs = [&](auto &&self, const int v, const int p, const int d, int h) -> void {
depth[v] = d;
if (depth[v] + dist[v] > depth[h] + dist[h]) {
h = v;
}
ac[v] = h;
for (const int t : tree[v]) {
if (t == p) {
continue;
}
self(self, t, v, d + 1, h);
}
};
dfs(dfs, 0, -1, 0, 0);
std::sort(O.begin(), O.end(), [&](const int a, const int b) {
return depth[a] > depth[b];
});
std::vector<bool> seen(N);
std::vector<int> dist2(N, -1), answer;
for (int i = 0; i < K; ++i) {
if (seen[O[i]]) {
continue;
}
que.push(ac[O[i]]);
seen[ac[O[i]]] = true;
answer.push_back(ac[O[i]]);
dist2[ac[O[i]]] = 0;
while (not que.empty()) {
const int f = que.front();
que.pop();
if (dist2[f] >= depth[O[i]] - depth[ac[O[i]]]) {
continue;
}
for (const int t : tree[f]) {
if (seen[t]) {
continue;
}
dist2[t] = dist2[f] + 1;
seen[t] = true;
que.push(t);
}
}
}
std::sort(answer.begin(), answer.end());
std::cout << answer.size() << std::endl;
for (int i = 0; i < (int)answer.size(); ++i) {
std::cout << answer[i] + 1;
std::cout << (i == (int)answer.size() - 1 ? '\n' : ' ');
}
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
342 ms |
65340 KB |
Output is correct |
2 |
Correct |
375 ms |
65228 KB |
Output is correct |
3 |
Correct |
387 ms |
65356 KB |
Output is correct |
4 |
Correct |
509 ms |
72184 KB |
Output is correct |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
4 ms |
696 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
2 ms |
468 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
681 ms |
46940 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |