Submission #394530

#TimeUsernameProblemLanguageResultExecution timeMemory
394530couplefirePastiri (COI20_pastiri)C++17
100 / 100
961 ms150640 KiB
#include <bits/stdc++.h> using namespace std; #define MAXN 500005 int n, k; vector<int> adj[MAXN]; vector<int> newadj[MAXN]; int dist[MAXN], good[MAXN], depth[MAXN]; bool sheep[MAXN], visited[MAXN]; vector<int> curstack[2*MAXN]; set<array<int, 2>, greater<array<int, 2>>> active; vector<int> ans; void bfs(){ memset(dist, 63, sizeof dist); queue<int> q; for(int i = 0; i<n; i++) if(sheep[i]) q.push(i), dist[i] = 0; while(!q.empty()){ int v = q.front(); q.pop(); for(auto u : adj[v]) if(dist[u] > dist[v]+1) dist[u] = dist[v]+1, q.push(u); } } void dfs(int v, int p, int d){ depth[v] = d; curstack[depth[v]+dist[v]].push_back(v); if(sheep[v]) good[v] = curstack[depth[v]+dist[v]].front(); for(auto u : adj[v]){ if(u == p) continue; dfs(u, v, d+1); } curstack[depth[v]+dist[v]].pop_back(); } void deactive(int v){ visited[v] = 1; if(sheep[v]) active.erase({depth[v], v}); for(auto u : newadj[v]){ if(visited[u]) continue; deactive(u); } } int main(){ // freopen("a.in", "r", stdin); ios_base::sync_with_stdio(false); cin.tie(0); cin >> n >> k; for(int i = 0; i<n-1; i++){ int a, b; cin >> a >> b; --a; --b; adj[a].push_back(b); adj[b].push_back(a); } for(int i = 0; i<k; i++){ int a; cin >> a; --a; sheep[a] = 1; } bfs(); dfs(0, 0, 0); for(int v = 0; v<n; v++){ for(auto u : adj[v]) if(dist[u] == dist[v]-1) newadj[v].push_back(u); } for(int v = 0; v<n; v++){ if(sheep[v]) active.insert({depth[v], v}); } while(!active.empty()){ int v = (*active.begin())[1]; ans.push_back(good[v]); deactive(good[v]); } cout << ans.size() << endl; for(auto x : ans) cout << x+1 << " "; cout << endl; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...