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>
using namespace std;
#define all(fl) fl.begin(),fl.end()
#define pb push_back
#define fi first
#define se second
#define for1(i,j,k) for(int i=j;i<=k;i++)
#define for2(i,j,k) for(int i=j;i>=k;i--)
#define for3(i,j,k,l) for(int i=j;i<=k;i+=l)
#define lb lower_bound
#define ub upper_bound
#define sz(a) (int)a.size()
#define pii pair<int,int>
#define pli pair<long long,int>
#define gcd __gcd
#define lcm(x,y) x*y/__gcd(x,y)
#define int long long
const int maxn=2e5+9;
vector<int>a[maxn];
int b[maxn];
int rev[maxn];
int dep[maxn];
int st[maxn][19];
void dfs(int u,int par){
for (auto v:a[u]){
if (v==par)continue;
dep[v]=dep[u]+1;
st[v][0]=u;
for1(i,1,18){
st[v][i]=st[st[v][i-1]][i-1];
}
dfs(v,u);
}
}
long long f[maxn];
int lca(int u,int v){
if (dep[u]<dep[v])swap(u,v);
int k=dep[u]-dep[v];
for2(i,18,0){
if (k>>i&1)u=st[u][i];
}
if (u==v)return u;
for2(i,18,0){
if (!st[u][i]||!st[v][i])continue;
if (st[u][i]!=st[v][i]){
u=st[u][i];
v=st[v][i];
}
}
return st[u][0];
}
long long dis(int u,int v){
return dep[u]+dep[v]-2*dep[lca(u,v)];
}
int c[maxn],mx[maxn];
int findset(int u){
if (c[u]<0)return u;
return c[u]=findset(c[u]);
}
void unite(int u,int v){
u=findset(u),v=findset(v);
if (u==v)return ;
if (mx[u]<mx[v])swap(u,v);
f[u]=max(f[u],f[v]+dis(rev[mx[u]],rev[mx[v]]));
mx[u]=max(mx[u],mx[v]);
c[u]+=c[v];
c[v]=u;
}
int32_t main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
//freopen("temp.INP","r",stdin);
//freopen("temp.OUT","w",stdout);
int n;
cin>>n;
for1(i,1,n){
cin>>b[i];
rev[b[i]]=i;
}
for1(i,1,n-1){
int u,v;
cin>>u>>v;
a[u].pb(v);
a[v].pb(u);
}
int root;
for1(i,1,n)if (b[i]==n)root=i;
dfs(root,0);
for1(i,1,n){
c[i]=-1;
mx[i]=b[i];
}
for1(i,1,n){
for(auto v:a[rev[i]]){
if (b[v]<i){
unite(v,rev[i]);
}
}
}
cout<<f[findset(root)];
}
Compilation message (stderr)
Main.cpp: In function 'int32_t main()':
Main.cpp:100:20: warning: 'root' may be used uninitialized in this function [-Wmaybe-uninitialized]
100 | cout<<f[findset(root)];
| ~~~~~~~^~~~~~
# | 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... |