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 duc_debug
#include "bits/debug.h"
#else
#define debug(...)
#endif
#define int long long
const int maxn = 5e5+5;
int n, k, x[maxn];
vector<int> g[maxn];
int d[maxn], h[maxn], choose[maxn], ok[maxn];
void bfs(){
memset(d, 0x3f3f3f, sizeof(d));
queue<int> q;
for(int i = 1; i <= k; ++i){
d[x[i]] = 0;
q.push(x[i]);
}
while(!q.empty()){
int u = q.front();
q.pop();
for(auto v:g[u]){
if(d[v] > d[u] + 1){
d[v] = d[u] + 1;
q.push(v);
}
}
}
}
void pre_dfs(int u, int prev, int mx, int st){
if(h[u] + d[u] > mx){
mx = h[u] + d[u];
st = u;
}
choose[u] = st;
for(auto v:g[u]){
if(v == prev) continue;
h[v] = h[u] + 1;
pre_dfs(v, u, mx, st);
}
}
void dfs(int u){
ok[u] = 1;
for(auto v:g[u]){
if(!ok[v] and d[v] + 1 == d[u]) dfs(v);
}
}
void solve(){
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);
}
for(int i = 1; i <= k; ++i) cin >> x[i];
bfs();
pre_dfs(1, 0, 0, 1);
sort(x + 1, x + k + 1, [](const int &u, const int &v) ->bool{
return h[u] > h[v];
});
vector<int> res;
for(int i = 1; i <= k; ++i){
if(!ok[x[i]]){
res.push_back(choose[x[i]]);
dfs(choose[x[i]]);
}
}
cout << res.size() << '\n';
for(auto i:res) cout << i << " ";
}
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
int test = 1;
// cin >> test;
for(int i = 1; i <= test; i++){
// cout << "Case " << "#" << i << ": ";
solve();
}
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... |