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
| class Solution { public int collectTheCoins(int[] coins, int[][] edges) { int n = coins.length; List<Integer>[] g = new ArrayList[n]; Arrays.setAll(g, e -> new ArrayList<>()); int[] degree = new int[n]; for (int[] e : edges) { int x = e[0], y = e[1]; g[x].add(y); g[y].add(x); ++degree[x]; ++degree[y]; } int leftEdges = n - 1; Deque<Integer> q = new ArrayDeque<>(); for (int i = 0; i < n; ++i) { if (degree[i] == 1 && coins[i] == 0) { q.offer(i); } } while (!q.isEmpty()) { --leftEdges; int x = q.poll(); for (int y : g[x]) { if (--degree[y] == 1 && coins[y] == 0) { q.offer(y); } } }
for (int i = 0; i < n; ++i) { if (degree[i] == 1 && coins[i] == 1) { q.offer(i); } } leftEdges -= q.size(); for (int x : q) { for (int y : g[x]) { if (--degree[y] == 1) { --leftEdges; } } } return Math.max(leftEdges * 2, 0); } }
|