Submission #948327

#TimeUsernameProblemLanguageResultExecution timeMemory
948327NeroZeinPastiri (COI20_pastiri)C++17
49 / 100
1098 ms114672 KiB
#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) { covered[v] = true; for (int u : g[v]) { if (u == p) continue; if (closest[u] == closest[v] - 1) { dfs2(u, v); } } } int lca(int u, int v) { if (dep[u] < dep[v]) swap(u, v); for (int j = 0; j < LOG; ++j) { if ((dep[u] - dep[v]) >> j & 1) { u = pr[j][u]; } } if (u == v) return v; for (int j = LOG - 1; j >= 0; --j) { if (pr[j][u] != pr[j][v]) { u = pr[j][u]; v = pr[j][v]; } } return pr[0][v]; } int dist(int u, int v) { return dep[u] + dep[v] - 2 * dep[lca(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; //this part can be sped up with binary jumping. for (int j = LOG - 1; j >= 0; --j) { if (closest[pr[j][newShephered]] == up + (1 << j)) { newShephered = pr[j][newShephered]; up += 1 << j; } } //while (pr[0][newShephered] != 0 && closest[pr[0][newShephered]] == up + 1) { //newShephered = pr[0][newShephered]; //up++; //} dfs2(newShephered, newShephered); shepherds.push_back(newShephered); } sort(shepherds.begin(), shepherds.end()); cout << shepherds.size() << '\n'; for (int shepherd : shepherds) { cout << shepherd << ' '; } 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...