#include <iostream>
#include <vector>
#include <algorithm>
#include <cassert>
#include <map>
using ll = long long;
#define debug(x) #x << " = " << x << '\n'
void merge(std::map<int, ll> &a, const std::map<int, ll> &b) {
  for (auto &[h, v] : a) {
    ll best = 0;
    for (const auto &[x, y] : b) {
      if (x <= h) {
        best = std::max(best, y);
      }
    }
    v += best;
  }
}
signed main() {
  std::ios_base::sync_with_stdio(false);
  std::cin.tie(0);
  int n;
  std::cin >> n;
  std::vector<int> h(n), c(n);
  std::vector<std::vector<int>> g(n);
  ll answer = 0;
  for (int i = 0; i < n; i++) {
    int p;
    std::cin >> p >> h[i] >> c[i];
    p--;
    answer += c[i];
    if (p != i) {
      g[p].push_back(i);
    }
  }
  std::vector<std::map<int, ll>> dp(n);
  auto keepBest = [&](int u) {
    std::vector<std::pair<int, ll>> st;
    std::vector<int> rem;
    for (const auto &[h, c] : dp[u]) {
      while (!st.empty() && st.back().second <= c) {
        rem.push_back(st.back().first);
        st.pop_back();
      }
      st.push_back({h, c});
    }
    for (int h : rem) {
      dp[u].erase(h);
    }
  };
  auto merge = [&](int u, int v) {
    for (const auto &[h, c] : dp[u]) {
      dp[u][h] += (dp[v].lower_bound(h)) -> second;
    }
  };
  auto dfs = [&](auto &&self, int u) -> void {
    int heavySon = -1;
    for (int v : g[u]) {
      self(self, v);
      if (heavySon == -1 || dp[v].size() > dp[heavySon].size()) {
        heavySon = v;
      }
    }
    if (heavySon == -1) {
      dp[u][1] = dp[u][+1e9] = 0;
      dp[u][h[u]] = c[u];
      keepBest(u);
      return;
    }
    std::swap(dp[u], dp[heavySon]);
    if (!dp[u].count(h[u])) {
      dp[u][h[u]] = 0;
    }
    g[u].erase(std::find(g[u].begin(), g[u].end(), heavySon));
    for (int v : g[u]) {
      for (const auto &[h, c] : dp[v]) {
        if (!dp[u].count(h)) {
          dp[u][h] = 0;
        }
      }
    }
    
    for (int v : g[u]) {
      merge(u, v);
    }
    dp[u][h[u]] += c[u]; 
    keepBest(u);
  };
  dfs(dfs, 0);
  ll maxi = 0;
  for (const auto &[x, y] : dp[0]) {
    maxi = std::max(maxi, y); 
  }
  
  answer -= maxi;
  std::cout << answer;
  
  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... |