#include<bits/stdc++.h>
using namespace std;
const int maxn = 3e5;
int n;
long long init, res;
pair<long long, int> a[maxn + 1];
vector<int> adj[maxn + 1];
vector<pair<long long, long long>> vec[maxn + 1];
inline void DFS(int u){
for (int v : adj[u])
DFS(v);
for (int v : adj[u]){
if (vec[v].size() > vec[u].size())
swap(vec[v], vec[u]);
for (pair<long long, long long> x : vec[v])
vec[u].push_back(x);
}
sort(vec[u].begin(), vec[u].end(), [](pair<long long, long long> x, pair<long long, long long> y){
return x.first < y.first || (x.first == y.first && x.second < y.second);
});
pair<long long, int> cur = {min(0LL, a[u].first), a[u].first};
while(!vec[u].empty() && cur.second <= 0){
auto [cost, earn] = vec[u].back();
vec[u].pop_back();
cur.first = min(cur.first, cur.second + cost);
cur.second += earn;
}
// if (cur.second > 0) vec[u].push_back(cur);
// cout << u << ' ' << vec[u].size() << '\n';
// for (auto [x, y] : vec[u]) cout << x << "-" << y << ' ';
// cout << '\n';
return;
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> init;
for (int i = 1; i <= n; ++i){
cin >> a[i].first >> a[i].second;
adj[a[i].second].push_back(i);
}
DFS(0);
sort(vec[0].begin(), vec[0].end(), [](pair<long long, long long> x, pair<long long, long long> y){
return x.first < y.first || (x.first == y.first && x.second < y.second);
});
while(!vec[0].empty()){
auto [cost, earn] = vec[0].back();
vec[0].pop_back();
if (init + res + cost < 0) break;
res += earn;
}
cout << res;
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... |