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<bits/stdc++.h>
using namespace std;
#ifdef DEBUG
auto&operator <<(auto& o, pair<auto, auto> p) {return o<<"("<<p.first<<", "<<p.second<<")";}
auto operator <<(auto& o, auto x)->decltype(x.end(), o) {o<<"{"; for(auto v : x) o<<v<<", "; return o<<"}";}
#define debug(X) cout<<"["#X"]"<<X<<endl;
#else
#define debug(X) {}
#endif
#define int long long
const long long INF = numeric_limits<long long>::max();
const int MAXN = 3*(1e5)+10;
vector<vector<int> > graph(MAXN);
vector<int> cost(MAXN);
vector<int> ms(MAXN);
void dfs(int b)
{
priority_queue<pair<int, int> > q;
for(auto v : graph[b]) {dfs(v); q.push({-ms[v], v});};
if(cost[b] >= 0) return;
ms[b] = -cost[b];
int akt = cost[b];
while(!q.empty())
{
auto a = q.top().second;
q.pop();
if(ms[a] == INF) break;
ms[b] = max(ms[b], ms[a]-akt);
akt += cost[a];
if(akt >= 0) break;
for(auto v : graph[a]) q.push({-ms[v], v});
}
if(akt < 0) ms[b] = INF;
}
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, s;
cin>>n>>s;
for(int i=1;i<=n;i++)
{
int c, p;
cin>>c>>p;
graph[p].push_back(i);
cost[i] = c;
}
dfs(0);
debug(ms);
int org = s;
priority_queue<pair<int, int> > q;
q.push({0, 0});
while(!q.empty())
{
auto a = q.top().second;
q.pop();
if(ms[a] > s) break;
if(s + cost[a] < 0) break;
s += cost[a];
for(auto v : graph[a]) q.push({-ms[v], v});
}
cout<<s - org;
}
# | 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... |