[LeetCode] Choose Edges to Maximize Score in a Tree

2378. Choose Edges to Maximize Score in a Tree

You are given a weighted tree consisting of n nodes numbered from 0 to n - 1.

The tree is rooted at node 0 and represented with a 2D array edges of size n where edges[i] = [pari, weighti] indicates that node pari is the parent of node i, and the edge between them has a weight equal to weighti. Since the root does not have a parent, you have edges[0] = [-1, -1].

Choose some edges from the tree such that no two chosen edges are adjacent and the sum of the weights of the chosen edges is maximized.

Return the maximum sum of the chosen edges.

Note:

  • You are allowed to not choose any edges in the tree, the sum of weights in this case will be 0.
  • Two edges Edge1 and Edge2 in the tree are adjacent if they have a common node.
  • In other words, they are adjacent if Edge1 connects nodes a and b and Edge2 connects nodes b and c.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
vector<vector<pair<long long, long long>>> adj;
pair<long long, long long> dfs(int u) {
long long inc = 0, exc = 0;
for(auto& [v,w] : adj[u]) {
auto [vinc, vexc] = dfs(v);
inc = max(inc, w + vexc - vinc);
exc += vinc;
}
return {inc + exc, exc};
}
public:
long long maxScore(vector<vector<int>>& A) {
int n = A.size();
adj = vector<vector<pair<long long, long long>>>(n);
for(int i = 1; i < n; i++) {
int par = A[i][0], w = A[i][1];
adj[par].push_back({i,max(0,w)});
}
auto [inc, _] = dfs(0);
return inc;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/22/PS/LeetCode/choose-edges-to-maximize-score-in-a-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.