Please Help DFS code explaination

I want to solve this question as i am new to trees and i could not able to understand the editorial.
https://www.codechef.com/APRIL19B/problems/SUBREM

int dfs(int v = 1, int p = 1) {
int res = 0;
for(auto u: g[v]) {
if(u != p) {
res += dfs(u, v);
}
}
return max(A[v] + res, -x);
}

I could not able to understand how this code works.Please help me to clarify my problem ...
There isn't enough info here to tell what the code is doing. Can you post the rest of the code?

Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <bits/stdc++.h>

using namespace std;

#define all(x) begin(x), end(x)
#define int int64_t

const int maxn = 1e5 + 42;
vector<int> g[maxn];
int x;
int A[maxn];

void init() {
	for(int i = 0; i < maxn; i++) {
		g[i].clear();
	}
}

int dfs(int v = 1, int p = 1) {
	int res = 0;
	for(auto u: g[v]) {
		if(u != p) {
			res += dfs(u, v);
		}
	}
	return max(A[v] + res, -x);
}

void solve() {
	init();
	int n;
	cin >> n >> x;
	for(int i = 1; i <= n; i++) {
		cin >> A[i];
	}
	for(int i = 1; i < n; i++) {
		int x, y;
		cin >> x >> y;
		g[x].push_back(y);
		g[y].push_back(x);
	}
	cout << dfs() << endl;
}

signed main() {
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	ios::sync_with_stdio(0);
	cin.tie(0);
	int t;
	cin >> t;
	while(t--) {
		solve();
	}
	return 0;
}
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);
}

Topic archived. No new replies allowed.