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 = 5e5 + 10;
int n, k, a[N], par[N], h[N];
vector<int> g[N];
// set<int> poss[N];
bool mark[N];
map<int, bool> exist;
vector<int> dist2(N, N + 10);
vector<int> bfs(vector<int> sources){
vector<int> dist(n + 1, N + 10);
queue<int> q;
for (int v : sources){
dist[v] = 0;
// poss[v] = {v};
q.push(v);
}
while (!q.empty()){
int v = q.front();
q.pop();
for (int u : g[v]){
if (dist[u] > dist[v] + 1){
q.push(u);
dist[u] = dist[v] + 1;
// poss[u] = poss[v];
}
// else if (dist[u] == dist[v] + 1){
// for (int x : poss[v])
// poss[u].insert(x);
// }
}
}
return dist;
}
void bfs2(int v, int d){
dist2[v] = 0;
queue<int> q;
q.push(v);
while (!q.empty()){
int v = q.front();
q.pop();
mark[v] = 1;
// cout << "Marked " << v << endl;
if (dist2[v] == d) continue;
for (int u : g[v]){
// cout << "Checking " << u << " at distance = " << dist2[u] << endl;
if (dist2[u] > dist2[v] + 1){
dist2[u] = dist2[v] + 1;
q.push(u);
// cout << "Pusing " << u << " in the queue" << endl;
}
}
}
}
void dfs(int v, int p = -1){
par[v] = p;
for (int u : g[v]){
if (u == p) continue;
h[u] = h[v] + 1;
dfs(u, v);
}
}
int main(){
cin >> n >> k;
for (int i = 1; i < n; i ++){
int u, v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
vector<int> vec;
for (int i = 0; i < k; i ++)
cin >> a[i], vec.push_back(a[i]), exist[a[i]] = 1;
dfs(1);
set<pair<int, int>> st;
for (int i = 0; i < k; i ++)
st.insert({h[a[i]], a[i]});
vector<int> dist = bfs(vec);
vector<int> res;
while (!st.empty()){
int v = (*st.rbegin()).second;
st.erase({h[v], v});
// cout << endl;
// cout << "At vertex = " << v << endl;
if (mark[v]) continue;
int cur = v;
while (par[cur] != -1 and dist[par[cur]] == (h[v] - h[par[cur]]))
cur = par[cur];
bfs2(cur, dist[cur]);
res.push_back(cur);
// cout << "Selected " << cur << endl;
// cout << endl;
}
cout << res.size() << endl;
for (int x : res)
cout << x << " ";
cout << endl;
}
# | 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... |