제출 #1060227

#제출 시각아이디문제언어결과실행 시간메모리
1060227gygCat in a tree (BOI17_catinatree)C++17
100 / 100
832 ms255712 KiB
#include <bits/stdc++.h> using namespace std; using pii = pair<int, int>; const int MAX_N = 2e5 + 5; int n, k; array<vector<int>, MAX_N> adj; array<int, MAX_N> depth; void dfs(int u = 1, int par = -1) { for (int v : adj[u]) if (v != par) depth[v] = depth[u] + 1, dfs(v, u); } array<int, MAX_N> siz; array<bool, MAX_N> del; void update_siz(int u, int par = -1) { siz[u] = 1; for (int v : adj[u]) { if (v == par) continue; if (del[v]) continue; update_siz(v, u), siz[u] += siz[v]; } } int find_cent(int u, int tot_siz, int par = -1) { for (int v : adj[u]) { if (v == par) continue; if (del[v]) continue; if (siz[v] * 2 > tot_siz) return find_cent(v, tot_siz, u); } return u; } array<vector<int>, MAX_N> ancs; // Reversed array<unordered_map<int, int>, MAX_N> dist; array<vector<pii>, MAX_N> dists; // Smallest last for popping purposes void find_dists(int u, int d, int par, int cent) { dist[cent][u] = d, dists[cent].push_back({d, u}); ancs[u].push_back(cent); for (int v : adj[u]) { if (v == par) continue; if (del[v]) continue; find_dists(v, d + 1, u, cent); } } void build(int u = 1) { update_siz(u); int cent = find_cent(u, siz[u]); find_dists(cent, 0, -1, cent); sort(dists[cent].rbegin(), dists[cent].rend()); del[cent] = true; for (int v : adj[cent]) if (!del[v]) build(v); } array<bool, MAX_N> used; void update_used(int u) { for (int v : ancs[u]) { int d = k - dist[v][u]; while (dists[v].size() && (dists[v].back().first < d || used[dists[v].back().second])) { // sus used[dists[v].back().second] = true; dists[v].pop_back(); } } } vector<pii> order; int comp() { for (int u = 1; u <= n; u++) order.push_back({depth[u], u}); sort(order.rbegin(), order.rend()); int ans = 0; for (pii x : order) { int u = x.second; if (used[u]) continue; ans++; update_used(u); // cout << "DELETED: " << u << endl; // cout << "LEFT: "; // for (int v = 1; v <= n; v++) // if (!used[v]) cout << v << " "; // cout << endl; } return ans; } int main() { // freopen("cat.in", "r", stdin); cin >> n >> k; for (int u = 2; u <= n; u++) { int v; cin >> v; v++; adj[u].push_back(v), adj[v].push_back(u); } dfs(); build(); // for (int u = 1; u <= n; u++) { // cout << u << ": "; // for (pii x : dists[u][u]) cout << x.second << "," << x.first << " "; // cout << endl; // } int ans = comp(); cout << ans << '\n'; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...