#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);
  std::vector<int> norm;
  ll answer = 0;
  for (int i = 0; i < n; i++) {
    int p;
    std::cin >> p >> h[i] >> c[i];
    norm.push_back(h[i]);
    p--;
    answer += c[i];
    if (p != i) {
      g[p].push_back(i);
    }
  }
  std::sort(norm.begin(), norm.end());
  norm.erase(std::unique(norm.begin(), norm.end()), norm.end());
  
  for (int &x : h) {
    x = std::lower_bound(norm.begin(), norm.end(), x) - norm.begin() + 1;
  }
  std::vector<std::map<int, ll>> delta(n);
  
  auto dfs = [&](auto &&self, int u) -> void {
    for (int v : g[u]) {
      self(self, v);
    }
    for (int v : g[u]) {
      if (delta[u].size() < delta[v].size()) {
        std::swap(delta[u], delta[v]);
      }
      for (const auto &[h, c] : delta[v]) {
        delta[u][h] += c;
      }
    }
    delta[u][h[u]] += c[u];
    auto it = delta[u].lower_bound(h[u]);
    if (it == delta[u].begin()) {
      return;
    }
    it = std::prev(it);
    ll val = c[u];
    std::vector<int> rem;
    while (val) {
      ll take = std::min(val, it -> second);
      it -> second -= take;
      val -= take;
      if (it -> second == 0) {
        rem.push_back(it -> first);
      }
      if (it == delta[u].begin()) {
        break;
      }
      it = std::prev(it);
    }
    for (int h : rem) {
      delta[u].erase(h);
    }
  };
  dfs(dfs, 0);
  for (const auto &[h, c] : delta[0]) {
    answer -= c;
  }
  
  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... |