Submission #1095403

#TimeUsernameProblemLanguageResultExecution timeMemory
1095403sitablechairCat Exercise (JOI23_ho_t4)C++17
100 / 100
164 ms47312 KiB
#include<bits/stdc++.h> #define ll long long #define sz(x) (signed)x.size() #define pb push_back #define ff first #define ss second #define endl '\n' #define For(i,l,r) for(int i=l;i<=r;i++) #define ForD(i,l,r) for(int i=r;i>=l;i--) using namespace std; const int N=2e5+3; int n,p[N],d[N],par[20][N]; int mxChild[N]; ll f[N],dp[N]; vector<int> g[N]; int find_set(int a) { return (f[a]<0?a:f[a]=find_set(f[a])); } void unite(int u,int v) { int a=find_set(u),b=find_set(v); if (a==b) return; if (f[a]>f[b]) swap(a,b); f[a]+=f[b]; f[b]=a; } void predfs(int u,int p=0) { for(auto v: g[u]) if (v!=p) { d[v]=d[u]+1; par[0][v]=u; For(i,1,18) par[i][v]=par[i-1][par[i-1][v]]; predfs(v,u); } } int lca(int u,int v) { if (d[v]>d[u]) swap(u,v); int dd=d[u]-d[v]; For(i,0,18) if (dd>>i&1) u=par[i][u]; if (u==v) return u; ForD(i,0,18) if (par[i][u]!=par[i][v]) u=par[i][u],v=par[i][v]; return par[0][u]; } int dis(int u,int v) { return d[u]+d[v]-2*d[lca(u,v)]; } int main() { cin.tie(0)->sync_with_stdio(0); cin >> n; For(i,1,n) cin >> p[i]; For(i,1,n-1) { int u,v; cin >> u >> v; g[p[u]].pb(p[v]); g[p[v]].pb(p[u]); } f[1]=-1; dp[1]=0; mxChild[1]=1; predfs(1); For(i,2,n) { dp[i]=0; for(auto u: g[i]) { if (u>i) continue; dp[i]=max(dp[i],dp[mxChild[find_set(u)]]+dis(mxChild[find_set(u)],i)); } f[i]=-1; for(auto u: g[i]) if (u<=i) unite(i,u); mxChild[find_set(i)]=i; } cout << dp[n] << endl; 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...