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
| class Solution { public int[] minEdgeReversals(int n, int[][] edges) { List<int[]>[] g = new List[n]; Arrays.setAll(g, k -> new ArrayList<>()); for (var e : edges) { int u = e[0], v = e[1]; g[u].add(new int[]{v, 0}); g[v].add(new int[]{u, 1}); } int[] ans = new int[n]; ans[0] = dfs(0, -1, g); dfs2(0, -1, g, ans); return ans; } private int dfs(int x, int fa, List<int[]>[] g) { int res = 0; for (int t[] : g[x]) { int y = t[0], w = t[1]; if (y == fa) continue; res += dfs(y, x, g) + w; } return res; } private void dfs2(int x, int fa, List<int[]>[] g, int[] ans) { for (int t[] : g[x]) { int y = t[0], w = t[1]; if (y == fa) continue; ans[y] = ans[x] + (w == 0 ? 1 : -1); dfs2(y, x, g, ans); } } }
|