forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum-score-after-applying-operations-on-a-tree.cpp
72 lines (68 loc) · 2.41 KB
/
maximum-score-after-applying-operations-on-a-tree.cpp
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Time: O(n)
// Space: O(n)
// iterative dfs, tree dp
class Solution {
public:
long long maximumScoreAfterOperations(vector<vector<int>>& edges, vector<int>& values) {
vector<vector<int>> adj(size(values));
for (const auto& e : edges) {
adj[e[0]].emplace_back(e[1]);
adj[e[1]].emplace_back(e[0]);
}
const auto& iter_dfs = [&]() {
vector<int64_t> dp(size(values));
vector<tuple<int, int, int>> stk = {{1, 0, -1}};
while (!empty(stk)) {
const auto [step, u, p] = stk.back(); stk.pop_back();
if (step == 1) {
if (size(adj[u]) == (u ? 1 : 0)) {
dp[u] = static_cast<int64_t>(values[u]);
continue;
}
stk.emplace_back(2, u, p);
for (const auto& v : adj[u]) {
if (v != p) {
stk.emplace_back(1, v, u);
}
}
} else if (step == 2) {
int64_t total = 0;
for (const auto& v : adj[u]) {
if (v != p) {
total += dp[v];
}
}
dp[u] = min(total, static_cast<int64_t>(values[u])); // min(pick u, not pick u)
}
}
return dp[0];
};
return accumulate(cbegin(values), cend(values), 0ll) - iter_dfs();
}
};
// Time: O(n)
// Space: O(n)
// dfs, tree dp
class Solution2 {
public:
long long maximumScoreAfterOperations(vector<vector<int>>& edges, vector<int>& values) {
vector<vector<int>> adj(size(values));
for (const auto& e : edges) {
adj[e[0]].emplace_back(e[1]);
adj[e[1]].emplace_back(e[0]);
}
const function<int64_t (int, int)> dfs = [&](int u, int p) {
if (size(adj[u]) == (u ? 1 : 0)) {
return static_cast<int64_t>(values[u]);
}
int64_t total = 0;
for (const auto& v : adj[u]) {
if (v != p) {
total += dfs(v, u);
}
}
return min(total, static_cast<int64_t>(values[u])); // min(pick u, not pick u)
};
return accumulate(cbegin(values), cend(values), 0ll) - dfs(0, -1);
}
};