[LeetCode] Most Profitable Path in a Tree

2467. Most Profitable Path in a Tree

There is an undirected tree with n nodes labeled from 0 to n - 1, rooted at node 0. You are given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.

At every node i, there is a gate. You are also given an array of even integers amount, where amount[i] represents:

  • the price needed to open the gate at node i, if amount[i] is negative, or,
  • the cash reward obtained on opening the gate at node i, otherwise.

The game goes on as follows:

  • Initially, Alice is at node 0 and Bob is at node bob.
  • At every second, Alice and Bob each move to an adjacent node. Alice moves towards some leaf node, while Bob moves towards node 0.
  • For every node along their path, Alice and Bob either spend money to open the gate at that node, or accept the reward. Note that:
  • If the gate is already open, no price will be required, nor will there be any cash reward.
  • If Alice and Bob reach the node simultaneously, they share the price/reward for opening the gate there. In other words, if the price to open the gate is c, then both Alice and Bob pay c / 2 each. Similarly, if the reward at the gate is c, both of them receive c / 2 each.
  • If Alice reaches a leaf node, she stops moving. Similarly, if Bob reaches node 0, he stops moving. Note that these events are independent of each other.

Return the maximum net income Alice can have if she travels towards the optimal leaf node.

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
class Solution {
void dfs1(int u, int d, int p, vector<int>& dep, vector<int>& par, vector<vector<int>>& adj) {
par[u] = p;
dep[u] = d;
for(auto v : adj[u]) {
if(v == p) continue;
dfs1(v,d+1,u,dep,par,adj);
}
}
void dfs2(int u, int now, int par, int& res, vector<vector<int>>& adj, vector<int>& cost) {
now += cost[u];
bool fl = true;
for(auto v : adj[u]) {
if(v == par) continue;
dfs2(v,now,u,res,adj,cost);
fl = false;
}
if(fl) res = max(res,now);
}
public:
int mostProfitablePath(vector<vector<int>>& edges, int bob, vector<int>& amount) {
vector<vector<int>> adj(amount.size());
for(auto e : edges) {
int u = e[0], v = e[1];
adj[u].push_back(v);
adj[v].push_back(u);
}
vector<int> dep(amount.size());
vector<int> par(amount.size());
dfs1(0,0,-1,dep,par,adj);
int target = dep[bob], u = bob;
amount[bob] = 0;
for(int i = 0; i < (target + 1) / 2; i++) {
amount[u] = 0;
u = par[u];
}

if(target % 2 == 0) amount[u] /= 2;
int res = INT_MIN;
dfs2(0,0,-1,res,adj,amount);
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/13/PS/LeetCode/most-profitable-path-in-a-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.