Submission #781461

#TimeUsernameProblemLanguageResultExecution timeMemory
781461boris_mihovCat Exercise (JOI23_ho_t4)C++17
100 / 100
227 ms44676 KiB
#include <algorithm> #include <iostream> #include <numeric> #include <cassert> #include <vector> typedef long long llong; const int MAXLOG = 18; const int MAXN = 200000 + 10; const int INF = 1e9; int n; struct Sparse { int sparse[MAXLOG][MAXN]; int dep[MAXN]; void build(int par[], int d[]) { for (int i = 1 ; i <= n ; ++i) { sparse[0][i] = par[i]; dep[i] = d[i]; } for (int log = 1 ; (1 << log) <= n ; ++log) { for (int i = 1 ; i <= n ; ++i) { sparse[log][i] = sparse[log - 1][sparse[log - 1][i]]; } } } void equalize(int &u, int v) { for (int log = MAXLOG - 1 ; log >= 0 ; --log) { if (dep[sparse[log][u]] >= dep[v]) { u = sparse[log][u]; } } } int getLCA(int u, int v) { if (u == v) { return u; } for (int log = MAXLOG - 1 ; log >= 0 ; --log) { if (sparse[log][u] != sparse[log][v]) { u = sparse[log][u]; v = sparse[log][v]; } } return sparse[0][u]; } int findLCA(int u, int v) { if (dep[u] < dep[v]) { std::swap(u, v); } equalize(u, v); return getLCA(u, v); } int findDist(int u, int v) { return dep[u] + dep[v] - 2 * dep[findLCA(u, v)]; } }; struct DSU { int par[MAXN]; int dep[MAXN]; int root[MAXN]; void build() { for (int i = 1 ; i <= n ; ++i) { dep[i] = 1; par[i] = root[i] = i; } } int find(int u) { if (par[u] == u) return u; return par[u] = find(par[u]); } void connect(int u, int v) { u = find(u); v = find(v); assert(u != v); if (dep[u] < dep[v]) { std::swap(u, v); } if (dep[u] == dep[v]) { dep[v]++; } par[u] = v; } }; int d[MAXN]; int par[MAXN]; Sparse sparse; std::vector <int> g[MAXN]; llong dp[MAXN]; DSU dsu; void dfs(int node, int p) { par[node] = p; d[node] = d[p] + 1; for (const int &u : g[node]) { if (u == p) { continue; } dfs(u, node); } } void solve() { dfs(1, 0); dsu.build(); sparse.build(par, d); for (int i = 1 ; i <= n ; ++i) { for (const int &u : g[i]) { if (u > i) { continue; } dp[i] = std::max(dp[i], dp[dsu.root[dsu.find(u)]] + sparse.findDist(i, dsu.root[dsu.find(u)])); dsu.connect(i, u); } dsu.root[dsu.find(i)] = i; } std::cout << dp[n] << '\n'; } void input() { std::cin >> n; for (int i = 1 ; i <= n ; ++i) { std::cin >> d[i]; } for (int i = 2 ; i <= n ; ++i) { int u, v; std::cin >> u >> v; g[d[u]].push_back(d[v]); g[d[v]].push_back(d[u]); } } void fastIOI() { std::ios_base :: sync_with_stdio(0); std::cout.tie(nullptr); std::cin.tie(nullptr); } int main() { fastIOI(); input(); solve(); 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...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...