This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
/**
* author: wxhtzdy
* created: 12.02.2023 13:22:57
**/
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<int> h(n);
for (int i = 0; i < n; i++) {
cin >> h[i];
}
vector<vector<int>> g(n);
for (int i = 0; i < n - 1; i++) {
int u, v;
cin >> u >> v;
--u; --v;
g[u].push_back(v);
g[v].push_back(u);
}
const int L = 25;
vector<vector<int>> jump(n, vector<int>(L));
vector<int> dep(n);
function<void(int, int)> Dfs = [&](int v, int pv) {
dep[v] = dep[pv] + 1;
jump[v][0] = pv;
for (int j = 1; j < L; j++) {
jump[v][j] = jump[jump[v][j - 1]][j - 1];
}
for (int u : g[v]) {
if (u == pv) {
continue;
}
Dfs(u, v);
}
};
Dfs(0, 0);
auto LCA = [&](int v, int u) {
if (dep[v] > dep[u]) {
swap(v, u);
}
for (int j = L - 1; j >= 0; j--) {
if (dep[jump[u][j]] >= dep[v]) {
u = jump[u][j];
}
}
if (v == u) {
return v;
}
for (int j = L - 1; j >= 0; j--) {
if (jump[v][j] != jump[u][j]) {
v = jump[v][j];
u = jump[u][j];
}
}
return jump[v][0];
};
auto GetDist = [&](int v, int u) {
return dep[v] + dep[u] - 2 * dep[LCA(v, u)];
};
vector<int> par(n);
iota(par.begin(), par.end(), 0);
function<int(int)> get = [&](int x) {
return par[x] == x ? x : par[x] = get(par[x]);
};
vector<int> order(n);
iota(order.begin(), order.end(), 0);
sort(order.begin(), order.end(), [&](int i, int j) {
return h[i] < h[j];
});
vector<long long> dp(n);
for (int i : order) {
for (int j : g[i]) {
if (h[i] > h[j]) {
dp[i] = max(dp[i], dp[get(j)] + GetDist(i, get(j)));
par[get(j)] = i;
}
}
}
cout << dp[order[n - 1]] << '\n';
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... |