Here's a description of dfs(). I can't say for sure that it solves the problem.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// recursively determine the profit of the tree starting at node v.
// p is the parent node and it's passed in to prevent the function
// from recursing back to the parent.
int dfs(int v = 1, int p = 1) {
int res = 0;
for(auto u: g[v]) { // for each neighbor of node v
if(u != p) { // skip the parent
res += dfs(u, v); // add up the profits
}
}
// The profit if you keep this node is this node's value
// (A[v] plus the profit of all children (res).
// If you delete this node, the profit is the cost of
// deleting the node (-x).
return max(A[v] + res, -x);
}