This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC target("avx2")
#define ll long long
#define pii pair<ll,ll>
#define pll pair<ll,ll>
#define plx pair<ll,int>
#define f first
#define s second
#define pb push_back
#define all(x) x.begin(),x.end()
#define vi vector<int>
#define vl vector<ll>
#define vvi vector<vi>
using namespace std;
const int mxn=2e5+5;
vector<int>g[mxn];
int pr[mxn]{0},h[mxn]{0},up[mxn][20]{0},d[mxn]{0};
void dfs(int u,int p){
up[u][0]=p;
for(int i=1;i<20;i++)up[u][i]=up[up[u][i-1]][i-1];
for(auto v:g[u]){
if(v==p)continue;
d[v]=d[u]+1;dfs(v,u);
}
}
int get(int r){
return pr[r]==r?r:pr[r]=get(pr[r]);
}
int lca(int a,int b){
if(d[b]<d[a])swap(a,b);
for(int i=19;i>=0;i--)if(d[b]-(1<<i)>=d[a])b=up[b][i];
if(a==b)return a;
for(int i=19;i>=0;i--)if(up[a][i]!=up[b][i])a=up[a][i],b=up[b][i];
return up[a][0];
}
int cal(int a,int b){
return d[a]+d[b]-2*d[lca(a,b)];
}
ll dp[mxn]{0};
int main(){
ios_base::sync_with_stdio(0);cin.tie(0);
int n;cin>>n;iota(pr,pr+n+1,0);
for(int i=1;i<=n;i++)cin>>h[i];
for(int i=1;i<=n-1;i++){
int a,b;cin>>a>>b;
g[h[a]].pb(h[b]);g[h[b]].pb(h[a]);
}dfs(1,1);
for(int i=1;i<=n;i++){
for(auto v:g[i]){
int vv=get(v);
if(vv<i){
dp[i]=max(dp[i],dp[vv]+cal(i,vv));
pr[vv]=i;
}
}
}cout<<dp[n];
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |