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>
using namespace std;
typedef long long ll;
typedef priority_queue<pair<ll, ll>> pqii;
const int MAXN = 300005;
vector<int> adj[MAXN];
ll val[MAXN];
pqii dfs(int x){
pqii pq;
for (int nn : adj[x]){
auto join = dfs(nn);
if (pq.size() < join.size()) swap(pq, join);
while (!join.empty()){
pq.push(join.top()); join.pop();
}
}
if (val[x] > 0) pq.push({0, val[x]});
else{
ll mp = val[x], sum = val[x];
while (!pq.empty()){
ll jmp, js; tie(jmp, js) = pq.top();
if (sum <= 0){
pq.pop();
mp = min(mp, sum + jmp); sum += js;
}
else{
if (jmp < mp) break;
pq.pop(); sum += js;
}
}
if (sum > 0) pq.push({mp, sum});
}
return pq;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int nums; cin >> nums >> val[0];
for (int i = 1; i <= nums; i++){
int par; cin >> val[i] >> par;
adj[par].push_back(i);
}
auto pq = dfs(0);
ll ans = 0;
while (!pq.empty()){
ll mp, sum; tie(mp, sum) = pq.top(); pq.pop();
if (ans + mp >= 0) ans += sum;
else break;
}
cout << ans - val[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... |