Submission #877657

#TimeUsernameProblemLanguageResultExecution timeMemory
877657huutuanPastiri (COI20_pastiri)C++14
100 / 100
485 ms73676 KiB
#include<bits/stdc++.h> #define taskname "sheep" using namespace std; const int N=5e5+1; int n, k, a[N], dep[N], par[N], dist[N], del[N]; vector<int> g[N]; void bfs(){ memset(dist, -1, sizeof dist); queue<int> q; for (int i=1; i<=n; ++i) if (a[i]) q.push(i), dist[i]=0; while (q.size()){ int u=q.front(); q.pop(); for (int v:g[u]) if (dist[v]==-1){ dist[v]=dist[u]+1; q.push(v); } } } void dfs(int u, int p){ par[u]=p; for (int v:g[u]) if (v!=p){ dep[v]=dep[u]+1; dfs(v, u); } } void bfs(int root){ queue<int> q; vector<int> vv; q.push(root); while (q.size()){ int u=q.front(); q.pop(); for (int v:g[u]) if (!del[v] && dist[v]==dist[u]-1){ del[v]=1; q.push(v); } } } int32_t main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); // freopen(taskname".inp", "r", stdin); // freopen(taskname".out", "w", stdout); 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){ int x; cin >> x; a[x]=1; } bfs(); dfs(1, 0); vector<int> vv; for (int i=1; i<=n; ++i) if (a[i]) vv.push_back(i); sort(vv.begin(), vv.end(), [&](int x, int y){ return dep[x]<dep[y]; }); vector<int> ans; while (vv.size()){ int u=vv.back(); vv.pop_back(); int v=u; while (dist[par[v]]==dep[u]-dep[par[v]]) v=par[v]; ans.push_back(v); bfs(v); while (vv.size() && del[vv.back()]) vv.pop_back(); } cout << ans.size() << '\n'; for (int i:ans) cout << i << ' '; return 0; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...