-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleet215.cpp
More file actions
64 lines (50 loc) · 1.45 KB
/
leet215.cpp
File metadata and controls
64 lines (50 loc) · 1.45 KB
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
vector<int> adj[100000];
int parent[100000], Bob[100000];
class Solution {
public:
static void dfs(int i, int p) {
parent[i]=p;
for (int j : adj[i]) {
if (j==p) continue;
dfs(j, i);
}
}
static int dfs_sum(int i, int dist, int prev, vector<int>& amount) {
int alice=0;
if (dist < Bob[i]) alice=amount[i];
bool isLeaf=1;// set isLeaf flag
int maxLeafSum=INT_MIN;
[[unroll]]
for (int j : adj[i]) {
if (j==prev) continue;
isLeaf=0;// has child=> no leaf
maxLeafSum = max(maxLeafSum, dfs_sum(j, dist+1, i, amount));
}
return alice+(isLeaf?0:maxLeafSum);
}
static int mostProfitablePath(vector<vector<int>>& edges, int bob, vector<int>& amount) {
const int n=edges.size()+1;
[[unroll]]
for (int i=0; i < n; i++) adj[i].clear();
[[unroll]]
for (auto& e : edges) {
int u=e[0], v=e[1];
adj[u].push_back(v);
adj[v].push_back(u);
}
dfs(0, -1);
// Compute Bob's reach time
fill(Bob, Bob+n, INT_MAX);
[[unroll]]
for (int x=bob, move=0; x != -1; x=parent[x]) {
Bob[x]=move++;
}
return dfs_sum(0, 0, -1, amount);
}
};
auto init = []() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return 'c';
}();