Submission #1111865

#TimeUsernameProblemLanguageResultExecution timeMemory
1111865starchanCat Exercise (JOI23_ho_t4)C++17
100 / 100
151 ms63560 KiB
#include<bits/stdc++.h> using namespace std; #define int long long #define in array<int, 2> #define pb push_back #define pob pop_back #define fast() ios_base::sync_with_stdio(false); cin.tie(NULL) const int MX = 2e5+5; const int INF = 1e17; const int LOGM = 18; vector<int> adj[MX]; int par[LOGM][MX]; int dp[MX]; int dep[MX]; int tin[MX]; int tout[MX]; int T; void dfs(int u, int p) { tin[u] = ++T; par[0][u] = p; dep[u] = dep[p]+1; for(int v: adj[u]) { if(v == p) continue; dfs(v, u); } tout[u] = T; return; } int dist(int u, int v) { if(tin[u] > tin[v]) swap(u, v); if(tout[u] >= tout[v]) return dep[v]-dep[u]; int s = u; for(int i = LOGM-1; i >= 0; i--) { if(tout[par[i][s]] < tout[v]) s = par[i][s]; } s = par[0][s]; return dep[u]+dep[v]-2*dep[s]; } vector<int> bst(MX); vector<int> pa(MX, -1); int leader(int u) { if(pa[u] < 0) return u; return pa[u] = leader(pa[u]); } void merge(int u, int v) { u = leader(u); v = leader(v); if(u == v) return; if(pa[u] < pa[v]) swap(u, v); pa[v]+=pa[u]; bst[v] = max(bst[v], bst[u]); pa[u] = v; return; } signed main() { fast(); int n; cin >> n; vector<int> p(n+1); for(int i = 1; i <= n; i++) cin >> p[i]; for(int i = 1; i < n; i++) { int u, v; cin >> u >> v; u = p[u]; v = p[v]; adj[u].pb(v); adj[v].pb(u); } par[0][0] = 0; dep[0] = 0; tout[0] = n+5; dfs(1, 0); for(int i = 1; i < LOGM; i++) { for(int u = 1; u <= n; u++) par[i][u] = par[i-1][par[i-1][u]]; } for(int i = 1; i <= n; i++) bst[i] = i; for(int i = 1; i <= n; i++) { for(int j: adj[i]) { if(j < i) { int w = bst[leader(j)]; dp[i] = max(dp[i], dp[w]+dist(i, w)); merge(i, j); } } } cout << dp[n] << "\n"; 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...