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;
#ifdef Nero
#include "Deb.h"
#else
#define debug(...)
#endif
const int LOG = 20;
const int N = 5e5 + 5;
int dep[N];
int closest[N];
int pr[LOG][N];
bool covered[N];
vector<int> g[N];
void bfs(vector<int>& sheeps) {
memset(closest, -1, sizeof closest);
queue<int> que;
for (int sheep : sheeps) {
que.push(sheep);
closest[sheep] = 0;
}
while (!que.empty()) {
int v = que.front();
que.pop();
for (int u : g[v]) {
if (closest[u] == -1) {
closest[u] = closest[v] + 1;
que.push(u);
}
}
}
}
void dfs(int v, int p) {
for (int u : g[v]) {
if (u == p) continue;
dep[u] = dep[v] + 1;
pr[0][u] = v;
for (int j = 1; j < LOG; ++j) {
pr[j][u] = pr[j - 1][pr[j - 1][u]];
}
dfs(u, v);
}
}
void dfs2(int v, int p) {
if (covered[v]) return;
covered[v] = true;
for (int u : g[v]) {
if (u == p) continue;
if (closest[u] == closest[v] - 1) {
dfs2(u, v);
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, k;
cin >> n >> k;
for(int i = 0; i < n - 1; ++i) {
int u, v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
vector<int> sheeps(k);
for (int i = 0; i < k; ++i) {
cin >> sheeps[i];
}
dfs(1, 0);
bfs(sheeps);
sort(sheeps.begin(), sheeps.end(), [&](int u, int v) {
return dep[u] < dep[v];
});
vector<int> shepherds;
for (int i = k - 1; i >= 0; --i) {
int sheep = sheeps[i];
if (covered[sheep]) continue;
int up = 0;
int newShephered = sheep;
for (int j = LOG - 1; j >= 0; --j) {
if (closest[pr[j][newShephered]] == up + (1 << j)) {
newShephered = pr[j][newShephered];
up += 1 << j;
}
}
dfs2(newShephered, newShephered);
shepherds.push_back(newShephered);
}
cout << shepherds.size() << '\n';
for (int shepherd : shepherds) {
cout << shepherd << ' ';
}
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... |