제출 #729014

#제출 시각아이디문제언어결과실행 시간메모리
729014MilosMilutinovicCat Exercise (JOI23_ho_t4)C++14
100 / 100
644 ms60808 KiB
/**
 *    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 timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...