#include "bits/stdc++.h"
using namespace std;
#ifdef duc_debug
#include "bits/debug.h"
#else
#define debug(...)
#endif
const int maxn = 2e5 + 5;
const int LG = 18;
int n;
vector<int> g[maxn];
int p[maxn], rev[maxn];
int h[maxn], up[maxn][LG + 1], f[maxn];
void dfs(int u, int prev) {
for (auto v:g[u]) {
if (v == prev) continue;
h[v] = h[u] + 1;
up[v][0] = u;
for (int i = 1; i <= LG; ++i) {
up[v][i] = up[up[v][i - 1]][i - 1];
}
dfs(v, u);
}
}
int lca(int u, int v) {
if (h[u] < h[v]) swap(u, v);
for (int i = LG; i >= 0; --i) {
if ((h[u] - h[v]) >> i & 1) {
u = up[u][i];
}
}
if (u == v) return u;
for (int i = LG; i >= 0; --i) {
if (up[u][i] != up[v][i]) {
u = up[u][i], v = up[v][i];
}
}
return up[u][0];
}
int dist(int u, int v) {
return h[u] + h[v] - 2 * h[lca(u, v)];
}
int lab[maxn];
int find(int u) {
return lab[u] < 0 ? u : lab[u] = find(lab[u]);
}
void solve() {
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> p[i];
rev[p[i]] = i;
lab[i] = -1;
}
for (int i = 1; i < n; ++i) {
int u, v; cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
dfs(1, 0);
for (int i = 1; i <= n; ++i) {
int u = rev[i];
for (auto v:g[u]) {
if (p[v] < i) {
v = find(v);
f[u] = max(f[u], f[v] + dist(u, v));
}
}
for (auto v:g[u]) {
if (p[v] < i) {
lab[find(v)] = u;
}
}
}
cout << f[n];
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
solve();
return 0;
}
# | 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... |