This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <algorithm>
#include <iostream>
#include <numeric>
#include <cassert>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
typedef long long llong;
const int MAXN = 300000 + 10;
const int MOD = 1e9 + 7;
const llong INF = 1e18;
const int INTINF = 1e9;
int n;
llong a[MAXN];
std::vector <int> g[MAXN];
std::priority_queue <std::pair <llong,llong>> pq[MAXN];
void dfs(int node, int par)
{
    for (const int &u : g[node])
    {
        if (u == par)
        {
            continue;
        }
        dfs(u, node);
        if (pq[u].size() > pq[node].size())
        {
            std::swap(pq[u], pq[node]);
        }
        while (pq[u].size())
        {
            pq[node].push(pq[u].top());
            pq[u].pop();
        }
    }
    std::pair <llong,llong> curr = {std::max(0LL, -a[node]), a[node]};
    while (pq[node].size() && (-pq[node].top().first <= curr.first || curr.second <= 0))
    {
        auto [needed, gain] = pq[node].top();
        needed = -needed;
        pq[node].pop();
        curr.first = std::max(0LL, std::max(curr.first, needed - curr.second));
        curr.second += gain;
    }
    if (curr.second > 0) pq[node].push({-curr.first, curr.second});
    else
    {
        while (pq[node].size())
        {
            pq[node].pop();
        }
    }
}
void solve()
{
    dfs(1, 0);
    llong gained = 0;
    while (pq[1].size())
    {
        auto [needed, gain] = pq[1].top();
        needed = -needed;
        pq[1].pop();
        assert(gain > 0);
        if (needed > gained)
        {
            break;
        }
        gained += gain;
    }
    std::cout << gained - a[1] << '\n';
}
void input()
{
    std::cin >> n >> a[1]; n++;
    for (int i = 2 ; i <= n ; ++i)
    {
        int p;
        std::cin >> a[i] >> p;
        g[p + 1].push_back(i);
    }
}
void fastIOI()
{
    std::ios_base :: sync_with_stdio(0);
    std::cout.tie(nullptr);
    std::cin.tie(nullptr);
}
int main()
{
    fastIOI();
    input();
    solve();
    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... |