Submission #1001940

#TimeUsernameProblemLanguageResultExecution timeMemory
1001940LOLOLOJobs (BOI24_jobs)C++17
100 / 100
247 ms74440 KiB
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
 
#define           f     first
#define           s     second
#define           pb    push_back
#define           ep    emplace
#define           eb    emplace_back
#define           lb    lower_bound
#define           ub    upper_bound
#define       all(x)    x.begin(), x.end()
#define      rall(x)    x.rbegin(), x.rend()
#define   uniquev(v)    sort(all(v)), (v).resize(unique(all(v)) - (v).begin())
#define     mem(f,x)    memset(f , x , sizeof(f))
#define        sz(x)    (ll)(x).size()
#define  __lcm(a, b)    (1ll * ((a) / __gcd((a), (b))) * (b))
#define          mxx    *max_element
#define          mnn    *min_element
#define    cntbit(x)    __builtin_popcountll(x)
#define       len(x)    (int)(x.length())
 
const int N = 3e5 + 10;
vector <int> ed[N];
priority_queue <pair <ll, ll>> pq[N];
ll a[N];

void dfs(int u) {
    for (auto x : ed[u]) {
        dfs(x);
        if (sz(pq[x]) > sz(pq[u]))
            swap(pq[x], pq[u]);

        while (sz(pq[x])) {
            auto t = pq[x].top();
            pq[x].pop();
            pq[u].push(t);
        }
    }

    if (a[u] > 0) {
        pq[u].push({0, a[u]});
    } else {
        ll mn = a[u], sum = a[u];
        while (sz(pq[u])) {
            auto t = pq[u].top();
            if (sum <= 0) {
                mn = min(mn, sum + t.f);
                sum += t.s;
                pq[u].pop();
            } else {
                if (t.f < mn) 
                    break;

                sum += t.s;
                pq[u].pop();
            }
        }

        if (sum > 0)
            pq[u].push({mn, sum});
    }
}


ll solve() {
    int n;
    cin >> n >> a[0];

    for (int i = 1; i <= n; i++) {
        int x;
        cin >> a[i] >> x;
        ed[x].pb(i);
    }

    ll s = 0;
    dfs(0);

    while (sz(pq[0])) {
        auto t = pq[0].top();
        pq[0].pop();
        if (s + t.f >= 0) {
            s += t.s;
        } else {
            break;
        }
    }

    return s - a[0];
}
 
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
 
 
    int t = 1;
    //cin >> t;
 
    while (t--) {
        cout << solve() << '\n';
    }
 
    return 0;
} 
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...