#include<bits/stdc++.h>
using namespace std;
const int maxn = 3e5 + 5;
int n;
long long init_money, res;
pair<long long, int> a[maxn];
vector<int> adj[maxn];
struct sct{
bool operator ()(const pair<long long, long long>& a, const pair<long long, long long>& b) const {
return a.first > b.first || (a.first == b.first && a.second > b.second);
}
};
multiset<pair<long long, long long>, sct> ms[maxn];
inline void DFS(int u) {
for (int v : adj[u]) {
DFS(v);
if (ms[v].size() > ms[u].size()) {
swap(ms[u], ms[v]);
}
for (auto &x : ms[v]) {
ms[u].insert(x);
}
ms[v].clear();
}
pair<long long, long long> cur = {min(0LL, a[u].first), a[u].first};
while (!ms[u].empty() && (cur.second <= 0 || cur.first >= (*(ms[u].begin())).first)) {
auto it = ms[u].begin();
pair<long long, long long> best = *it;
ms[u].erase(it);
cur.first = min(cur.first, cur.second + best.first);
cur.second += best.second;
}
if (cur.second > 0) {
ms[u].insert(cur);
}
return;
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n >> init_money;
for (int i = 1; i <= n; ++i) {
cin >> a[i].first >> a[i].second;
adj[a[i].second].push_back(i);
}
DFS(0);
for (auto it = ms[0].begin(); it != ms[0].end(); ++it) {
auto [cost, earn] = *it;
if (init_money + 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... |