-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
maximum-points-after-collecting-coins-from-all-nodes.cpp
98 lines (93 loc) · 3.29 KB
/
maximum-points-after-collecting-coins-from-all-nodes.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Time: O(nlogr), r = max(coins)
// Space: O(n)
// dfs, bitmasks, pruning
class Solution {
public:
int maximumPoints(vector<vector<int>>& edges, vector<int>& coins, int k) {
static const int NEG_INF = numeric_limits<int>::min();
vector<vector<int>> adj(size(coins));
for (const auto& e : edges) {
adj[e[0]].emplace_back(e[1]);
adj[e[1]].emplace_back(e[0]);
}
const int mx = *max_element(cbegin(coins), cend(coins));
const int max_base = 1 << (mx != 0 ? __lg(mx) + 1 : 0);
vector<int> lookup(size(coins));
const function<int (int, int, int)> dfs = [&](int u, int p, int base) {
if (base >= max_base) {
return 0;
}
if (lookup[u] & base) { // we prefer the first way to the second way, so the visited state cannot improve the current chosen ways
return NEG_INF;
}
lookup[u] |= base;
int total1 = (coins[u] / base) - k;
for (const auto& v : adj[u]) {
if (v == p) {
continue;
}
const auto& r = dfs(v, u, base);
if (r == NEG_INF) {
total1 = r;
break;
}
total1 += r;
}
if ((coins[u] / base) - k >= coins[u] / (base << 1)) { // if (coins[u]//base)-k >= coins[u]//(base*2), the first way is always better
return total1;
}
int total2 = coins[u] / (base << 1);
for (const auto& v : adj[u]) {
if (v == p) {
continue;
}
const auto& r = dfs(v, u, base << 1);
if (r == NEG_INF) {
total2 = r;
break;
}
total2 += r;
}
return max(total1, total2);
};
return dfs(0, -1, 1);
}
};
// Time: O(nlogr), r = max(coins)
// Space: O(nlogr)
// tree dp, memoization
class Solution2 {
public:
int maximumPoints(vector<vector<int>>& edges, vector<int>& coins, int k) {
vector<vector<int>> adj(size(coins));
for (const auto& e : edges) {
adj[e[0]].emplace_back(e[1]);
adj[e[1]].emplace_back(e[0]);
}
const int mx = *max_element(cbegin(coins), cend(coins));
const int max_d = mx != 0 ? __lg(mx) + 1 : 0;
vector<vector<int>> lookup(size(coins), vector<int>(max_d, -1));
const function<int (int, int, int)> memoization = [&](int u, int p, int d) {
if (d >= max_d) {
return 0;
}
if (lookup[u][d] == -1) {
int total1 = (coins[u] >> d) - k;
for (const auto& v : adj[u]) {
if (v != p) {
total1 += memoization(v, u, d);
}
}
int total2 = coins[u] >> (d + 1);
for (const auto& v : adj[u]) {
if (v != p) {
total2 += memoization(v, u, d + 1);
}
}
lookup[u][d] = max(total1, total2);
}
return lookup[u][d];
};
return memoization(0, -1, 0);
}
};