#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define all(v) v.begin(),v.end()
typedef tuple<int,int,int> iii;
int n,s;
vector<int> x,toposort;
vector<vector<int>> adj;
vector<bool> vis;
vector<bool> al;
vector<vector<int>> liste;
void topo(int node){
if (vis[node]) return;
vis[node] = true;
for (auto x : adj[node]){
topo(x);
}
toposort.pb(node);
}
int dfs(int node){
if (vis[node]) return 0;
vis[node] = true;
int sm = x[node];
for (auto to : adj[node]){
int res = dfs(to);
sm += res;
}
if (sm > 0) {
al[node] = true;
liste.back().pb(node);
}
return max(sm,0);
}
int main(){
cin >> n >> s;
x.assign(n,0);
vis.assign(n,false);
adj.assign(n+10,vector<int>());
for (int i = 0; i < n; i++) {
int p; cin >> x[i] >> p;
if (p > 0) adj[p-1].pb(i);
}
for (int i = 0; i < n; i++) if (!vis[i]) topo(i);
reverse(all(toposort));
vis.assign(n,false);
al.assign(n,false);
for (auto x : toposort){
if (vis[x]) continue;
liste.pb(vector<int>());
dfs(x);
reverse(all(liste.back()));
}
priority_queue<iii> pq;
for (int i = 0; i < liste.size(); i++){
if (!liste[i].empty()) pq.push({x[liste[i][0]],i,0});
}
int mx = 0,sm = s;
while (!pq.empty() && s >= 0){
int val,i,j; tie(val,i,j) = pq.top(); pq.pop();
if (sm + val < 0) break;
sm += val;
if (j+1 < liste[i].size()){
pq.push({x[liste[i][j+1]],i,j+1});
}
mx = max(mx,sm - s);
}
cout << mx << endl;
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... |