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>
#define ll long long
#define ld long double
#define sp ' '
#define en '\n'
#define smin(a, b) a = min(a, b)
#define smax(a, b) a = max(a, b)
using namespace std;
const int N = 2e5 + 2;
const int inf = 2e9 + 2;
int p[N], inv[N];
int par[N][18], in[N], out[N], dep[N], tsz;
vector<int> g[N];
vector<array<int, 2>> ng[N];
void Dfs(int s, int e) {
in[s] = ++tsz;
par[s][0] = e;
for (int i = 1; i < 18; i++) par[s][i] = par[par[s][i - 1]][i - 1];
for (int u : g[s]) {
if (u == e) continue;
dep[u] = dep[s] + 1;
Dfs(u, s);
}
out[s] = tsz;
}
bool Ancestor(int u, int v) {
return in[u] <= in[v] && out[v] <= out[u];
}
int Lca(int u, int v) {
if (Ancestor(u, v)) return u;
if (Ancestor(v, u)) return v;
for (int i = 17; i >= 0; i--) {
if (par[u][i] && !Ancestor(par[u][i], v)) u = par[u][i];
}
return par[u][0];
}
struct Dsu {
int link[N], mx[N];
void Init(int n) {
for (int i = 1; i <= n; i++) {
link[i] = i;
mx[i] = p[i];
}
}
int Find(int x) {
if (x == link[x]) return x;
return link[x] = Find(link[x]);
}
void Unite(int x, int y) {
x = Find(x); y = Find(y);
if (mx[x] < mx[y]) swap(x, y);
link[y] = x;
}
}dsu;
ll Dfs1(int s, int e) {
ll ret = 0;
for (auto u : ng[s]) {
if (u[0] == e) continue;
smax(ret, Dfs1(u[0], s) + u[1]);
}
return ret;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n; cin >> n;
for (int i = 1; i <= n; i++) {
cin >> p[i];
inv[p[i]] = i;
}
vector<array<int, 3>> e(n - 1);
for (int i = 0; i < n - 1; i++) {
cin >> e[i][1] >> e[i][2];
e[i][0] = max(p[e[i][1]], p[e[i][2]]);
g[e[i][1]].push_back(e[i][2]);
g[e[i][2]].push_back(e[i][1]);
}
Dfs(1, 0);
sort(e.begin(), e.end());
dsu.Init(n);
for (auto u : e) {
int x = dsu.Find(u[1]);
int y = dsu.Find(u[2]);
x = inv[dsu.mx[x]];
y = inv[dsu.mx[y]];
dsu.Unite(x, y);
int d = dep[x] + dep[y] - 2 * dep[Lca(x, y)];
ng[x].push_back({y, d});
ng[y].push_back({x, d});
}
cout << Dfs1(inv[n], 0) << en;
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... |