#include <bits/stdc++.h>
using namespace std;
const int N = 200'000 + 10;
int n;
pair<int, int> cons[N];
vector<int> ad[N];
int sz[N];
void dfs(int u, int p = -1) {
for (const auto& v : ad[u]) {
if (v == p) continue;
dfs(v, u);
sz[u] += sz[v];
}
}
int head[N], par[N];
int st[N], ed[N], node[N], num;
void hld(int u, int p = -1) {
if (!head[u]) head[u] = u;
st[u] = ++num; node[num] = u;
sort(ad[u].begin(), ad[u].end(), [&](const auto& i, const auto& j) {
return sz[i] > sz[j];
});
bool goHeavy = false;
for (const auto& v : ad[u]) {
if (v == p) continue;
if (!goHeavy) goHeavy = true, head[v] = head[u];
par[v] = u;
hld(v, u);
}
ed[u] = num;
}
set<pair<int, int>> proc[N];
int32_t main() {
cin.tie(0)->sync_with_stdio(0);
cin >> n;
for (int i = 1; i <= n; ++i) {
int p; cin >> p;
if (p != i) {
ad[p].push_back(i);
ad[i].push_back(p);
}
cin >> cons[i].first >> cons[i].second;
}
dfs(1);
hld(par[1] = 1);
vector<int> order(n); iota(order.begin(), order.end(), 1);
sort(order.begin(), order.end(), [&](const auto& i, const auto& j) {
return make_pair(cons[i].first, st[i]) > make_pair(cons[j].first, st[j]);
});
long long answer = 0;
for (auto u : order) {
int saveU = u;
int value = cons[u].second;
for (; value; u = par[head[u]]) {
vector<pair<int, int>> add, del;
auto it = proc[head[u]].upper_bound({st[u] + 1, 0});
while (it != proc[head[u]].begin()) {
it = prev(it);
auto [p, tag] = *it;
del.push_back(*it);
if (value > tag) {
value -= tag;
} else {
if (tag > value) add.push_back({p, tag - value});
value = 0;
break;
}
}
for (const auto& it : del) proc[head[u]].erase(it);
for (const auto& it : add) proc[head[u]].insert(it);
if (u == 1) break;
}
u = saveU;
proc[head[u]].insert({st[u], cons[u].second});
answer += value;
}
answer = -answer;
for (int i = 1; i <= n; ++i) answer += cons[i].second;
cout << answer << "\n";
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |