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
| class Solution { public int mostProfitablePath(int[][] edges, int bob, int[] amount) { n = edges.length + 1; graph = new List[n]; this.amount = amount; Arrays.setAll(graph, o -> new ArrayList<>()); time = new int[n]; Arrays.fill(time, n); for (int[] edge : edges) { int from = edge[0], to = edge[1]; graph[from].add(to); graph[to].add(from); } graph[0].add(-1); getDistFromRoot(bob, -1, 0); dfs(0, -1, 0, 0); return res; }
private void dfs(int alice, int parent, int aliceTime, int score) { if (aliceTime == time[alice]) score += amount[alice] / 2; if (aliceTime < time[alice]) score += amount[alice]; if (graph[alice].size() == 1) { res = Math.max(res, score); return; } for (int next : graph[alice]) if (next != parent) dfs(next, alice, aliceTime + 1, score); }
private boolean getDistFromRoot(int cur, int parent, int t) { if (cur == 0) { time[cur] = t; return true; } for (int next : graph[cur]) { if (next != parent && getDistFromRoot(next, cur, t + 1)) { time[cur] = t; return true; } } return false;
}
List<Integer>[] graph; int[] time; int n; int[] amount; int res = Integer.MIN_VALUE; }
|