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;
#ifdef DEBUG
auto& operator <<(auto& o, pair<auto, auto> p) {return o<<"{"<<p.first<<", "<<p.second<<"}";}
auto& operator <<(auto& o, auto x) {o<<"{"; for(auto v : x) o<<v<<", "; return o<<"}";}
#define debug(X) cerr<<"["#X"]: "<<X<<endl;
#else
#define debug(X) {}
#endif
#define int long long
const int INF = numeric_limits<int>::max();
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, s;
cin>>n>>s;
int org = s;
vector<vector<int> > graph(n+1);
vector<int> cost(n+1);
for(int i=1;i<=n;i++)
{
int p, c;
cin>>c>>p;
graph[p].push_back(i);
cost[i] = c;
}
vector<pair<int, int> > dp(n+1);
vector<unordered_set<int> > nwGraph(n+1);
function<void(int, int)> dfs = [&](int a, int par)
{
vector<pair<int, pair<int, int> > > sons;
for(auto v : graph[a])
if(v != par)
{
dfs(v, a);
sons.push_back({dp[v].first, {dp[v].second, v}});
}
sort(sons.begin(), sons.end(), [&](pair<int, pair<int, int> > a, pair<int, pair<int, int> > b)
{return make_pair(a.first, -a.second.first) < make_pair(b.first, -b.second.first);});
int k = -1, c = cost[a];
while(c < 0 && k != (int)sons.size()-1) {k++; c += sons[k].second.first;}
if(c < 0) {dp[a] = {INF, -INF}; return;}
int minS = -cost[a];
int pref = 0;
for(int i=0;i<=k;i++)
{
minS = max(minS, sons[i].first-pref-cost[a]);
pref += sons[i].second.first;
nwGraph[a].insert(sons[i].second.second);
}
dp[a] = {minS, c};
return;
};
dfs(0, -1);
priority_queue<pair<int, int> > q;
function<void(int, int)> del = [&](int a, int par)
{
s += cost[a];
for(auto v : graph[a])
if(nwGraph[a].find(v) == nwGraph[a].end())
q.push({-dp[v].first, v});
else
del(v, a);
};
q.push({0, 0});
while(!q.empty())
{
auto a = q.top();
debug(a);
q.pop();
if(-a.first > s) break;
del(a.second, -1);
}
cout<<s-org;
}
# | 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... |