#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define all(v) v.begin(),v.end()
int n,s;
vector<int> x,toposort;
vector<vector<int>> adj;
vector<bool> vis;
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 = max(0,dfs(to));
sm += res;
}
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;
p--;
if (p != -1) adj[p].pb(i);
}
for (int i = 0; i < n; i++) if (!vis[i]) topo(i);
reverse(all(toposort));
vis.assign(n,false);
int ans = 0;
for (auto x : toposort){
ans += dfs(x);
}
cout << ans + s << 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... |