#include <cstdio>
#include <stdio.h>
#include <stdbool.h>
#include <iostream>
#include <map>
#include <vector>
#include <climits>
#include <stack>
#include <string>
#include <queue>
#include <algorithm>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <cctype>
#include <bitset>
#include <iomanip>
#include <cstring>
#include <numeric>
#include <cassert>
using namespace std;
#define int long long
#define pii pair<int, int>
#define mp make_pair
#define pb push_back
#define fi first
#define se second
vector<int> depth, dsu, vect;
vector<vector<int> > graph, twok;
void dfs(int node, int p, int d){
depth[node]=d;
twok[node][0]=p;
for (int i=1; i<20; ++i)twok[node][i]=twok[twok[node][i-1]][i-1];
for (auto num:graph[node])if (num!=p)dfs(num, node, d+1);
}
int lca(int a, int b){
if (depth[a]<depth[b])swap(a, b);
for (int i=0, k=depth[a]-depth[b]; i<20; ++i)if (k&(1<<i))a=twok[a][i];
if (a==b)return a;
for (int i=19; i>=0; --i)if (twok[a][i]!=twok[b][i])a=twok[a][i], b=twok[b][i];
return twok[a][0];
}
int fp(int a){
if (dsu[a]==-1)return a;
return dsu[a]=fp(dsu[a]);
}
void merge(int a, int b){
a=fp(a), b=fp(b);
if (a==b)return;
if (vect[a]<vect[b])dsu[a]=b;
else dsu[b]=a;
}
int dist(int a, int b){
return depth[a]+depth[b]-2*depth[lca(a, b)];
}
int32_t main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, a, b;
cin>>n;
dsu.resize(n+1, -1);
graph.resize(n+1);
depth.resize(n+1);
vect.resize(n+1);
twok.resize(20, vector<int>(n+1));
vector<int> ord(n), dp(n+1, 0);
for (int i=1; i<=n; ++i)cin>>vect[i], ord[vect[i]-1]=i;
for (int i=1; i<n; ++i){
cin>>a>>b;
graph[a].pb(b);
graph[b].pb(a);
}
dfs(1, 1, 0);
for (auto node:ord)for (auto num:graph[node])if (vect[node]>vect[num])dp[node]=max(dp[node], dp[fp(num)]+dist(fp(num), node)), merge(num, node);
cout<<dp[ord.back()];
}
# | 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... |