#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long
#define ld long double
#define ull unsigned long long
#define ff first
#define ss second
#define pii pair<int,int>
#define pll pair<long long, long long>
#define vi vector<int>
#define vl vector<long long>
#define pb push_back
#define rep(i, b) for(int i = 0; i < (b); ++i)
#define rep2(i,a,b) for(int i = a; i <= (b); ++i)
#define rep3(i,a,b,c) for(int i = a; i <= (b); i+=c)
#define count_bits(x) __builtin_popcountll((x))
#define all(x) (x).begin(),(x).end()
#define siz(x) (int)(x).size()
#define forall(it,x) for(auto& it:(x))
using namespace __gnu_pbds;
using namespace std;
typedef tree<int, null_type, less<int>, rb_tree_tag,tree_order_statistics_node_update> ordered_set;
//mt19937 mt;void random_start(){mt.seed(chrono::time_point_cast<chrono::milliseconds>(chrono::high_resolution_clock::now()).time_since_epoch().count());}
//ll los(ll a, ll b) {return a + (mt() % (b-a+1));}
const int INF = 1e9+50;
const ll INF_L = 1e18+40;
const ll MOD = 1e9+7;
vi graph[300001];
ll cost[300001];
priority_queue<pll,vector<pll>,greater<pll>> pq[300001];
void merge(int a, int b)
{
if(siz(pq[b]) > siz(pq[a])) swap(pq[a],pq[b]);
while(!pq[b].empty())
{
auto it = pq[b].top();
pq[b].pop();
pq[a].push(it);
}
}
void dfs(int v)
{
bool was = 0;
forall(it,graph[v])
{
dfs(it);
if(!was)
{
was = 1;
swap(pq[it],pq[v]);
}
else merge(v,it);
}
pll add = {-1e18,-1e18};
if(cost[v] > 0) add = {-cost[v],cost[v]};
else
{
ll cost_add = cost[v];
ll lim = -cost[v];
while(siz(pq[v]) > 0 && (cost_add+pq[v].top().ss < 0))
{
cost_add += pq[v].top().ss;
lim = max(lim,max(0LL,pq[v].top().ff)-cost_add+pq[v].top().ss);
pq[v].pop();
}
if(siz(pq[v]) == 0) return;
add = {max(lim,pq[v].top().ff-cost_add),cost_add+pq[v].top().ss};
pq[v].pop();
}
while(siz(pq[v]) > 0 && pq[v].top().ff <= add.ff)
{
add.ss += pq[v].top().ss;
pq[v].pop();
}
pq[v].push(add);
}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
//random_start();
int n;
ll s;
cin >> n >> s;
rep2(i,1,n)
{
int p;
cin >> cost[i] >> p;
graph[p].pb(i);
}
dfs(0);
ll beg_s = s;
while(!pq[0].empty())
{
if(s < pq[0].top().ff) break;
s += pq[0].top().ss;
pq[0].pop();
}
cout << s-beg_s << "\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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |