Submission #1365836

#TimeUsernameProblemLanguageResultExecution timeMemory
1365836LIAJobs (BOI24_jobs)C++17
100 / 100
143 ms65396 KiB
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define v vector
#define lp(i, s, e) for (ll i = s; i < e; ++i)

struct st {
  ll req, profit;
  bool operator<(const st &other) const { return req > other.req; }
};

int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);

  ll n, s;
  cin >> n >> s;
  v<v<ll>> g(n);
  v<ll> bef(n), pro(n);
  lp(i, 0, n) {
    cin >> pro[i] >> bef[i];
    bef[i]--;
  }
  lp(i, 0, n) {
    if (bef[i] != -1)
      g[bef[i]].push_back(i);
  }

  v<st> after(n);
  v<priority_queue<st, v<st>>> pq(n);
  for (ll i = n - 1; i >= 0; --i) {
    after[i].req = (pro[i] > 0 ? 0 : -pro[i]);
    after[i].profit = pro[i];
    for (auto it : g[i]) {
      if (pq[i].size() < pq[it].size()) {
        swap(pq[i], pq[it]);
      }
      while (!pq[it].empty()) {
        pq[i].push(pq[it].top());
        pq[it].pop();
      }
    }
    while (!pq[i].empty()) {
      auto [req, prof] = pq[i].top();
      if (after[i].profit < 0 || after[i].req > req) {
        after[i].req = max(after[i].req, req - after[i].profit);
        after[i].profit += prof;
        pq[i].pop();
      } else
        break;
    }
    if (after[i].profit > 0) {
      pq[i].push(after[i]);
    }
  }

  priority_queue<st, v<st>> final_pq;
  lp(i, 0, n) {
    if (bef[i] == -1) {
      while (!pq[i].empty()) {
        final_pq.push(pq[i].top());
        pq[i].pop();
      }
    }
  }
  ll ans = 0;
  ll cur = s;
  while (!final_pq.empty()) {
    auto [req, prof] = final_pq.top();
    final_pq.pop();
    if (cur >= req && prof > 0) {
      cur += prof;
      ans += prof;
    } else {
      break;
    }
  }
  cout << ans << '\n';
}
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...