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>
#define ll long long
#define pqi priority_queue<pair<ll,ll>>
#define F first
#define S second
using namespace std;
const ll maxn=1e18;
ll n,s,pp[300010],p[300010];
vector<int> e[300010];
pqi dfs(int now){
pqi pq;
for(auto x:e[now]){
pqi pq2=dfs(x);
if(pq.size()<pq2.size())swap(pq,pq2);
while(!pq2.empty()){
pq.push(pq2.top());
pq2.pop();
}
}
ll need=min(0ll,pp[now]),pf=pp[now];
while(!pq.empty()&&pf<=0){
auto [x,y]=pq.top();
pf+=y;
need=min(need,x+pf);
pq.pop();
}
while(!pq.empty()&&pq.top().F+pf>=need){
pf+=pq.top().S;
pq.pop();
}
if(pf>0)pq.push({need,pf});
return pq;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cin>>n>>s;
for(int i=1;i<=n;i++){
int a,b;
cin>>a>>b;
pp[i]=a;
p[i]=b;
e[b].push_back(i);
}
pqi pq=dfs(0);
ll now=s,pf=0;
while(!pq.empty()&&now+pf+pq.top().F>=0){
//auto [x,y]=pq.top();
//cout<<x<<" "<<y<<' '<<"?\n";
pf+=pq.top().S;
pq.pop();
}
cout<<pf<<"\n";
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... |