|
| 1 | +```java |
| 2 | +import java.util.ArrayList; |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +public class PGM_LV2_전력망_둘로_나누기 { |
| 7 | + |
| 8 | + private static int N, ans; |
| 9 | + private static int[][] wires; |
| 10 | + private static boolean[] visited; |
| 11 | + private static List<Integer>[] graph; |
| 12 | + |
| 13 | + private static void init(int n, int[][] wire) { |
| 14 | + N = n; |
| 15 | + ans = Integer.MAX_VALUE; |
| 16 | + wires = wire; |
| 17 | + |
| 18 | + visited = new boolean[N + 1]; |
| 19 | + |
| 20 | + graph = new List[N + 1]; |
| 21 | + for (int i = 0; i <= N; i++) { |
| 22 | + graph[i] = new ArrayList<>(); |
| 23 | + } |
| 24 | + |
| 25 | + for (int[] edge : wires) { |
| 26 | + graph[edge[0]].add(edge[1]); |
| 27 | + graph[edge[1]].add(edge[0]); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + private static void sol() { |
| 32 | + int cnt; |
| 33 | + int left; |
| 34 | + for (int i = 0; i < N - 1; i++) { |
| 35 | + Arrays.fill(visited, false); |
| 36 | + |
| 37 | + visited[wires[i][0]] = true; |
| 38 | + visited[wires[i][1]] = true; |
| 39 | + |
| 40 | + cnt = exclude(wires[i][0], wires[i]); |
| 41 | + |
| 42 | + left = N - cnt; |
| 43 | + ans = Math.min(ans, Math.abs(cnt - left)); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + private static int exclude(int start, int[] target) { |
| 48 | + int cnt = 0; |
| 49 | + |
| 50 | + for (int n : graph[start]) { |
| 51 | + if (visited[n]) continue; |
| 52 | + |
| 53 | + visited[n] = true; |
| 54 | + cnt += exclude(n, target); |
| 55 | + } |
| 56 | + return cnt + 1; |
| 57 | + } |
| 58 | + |
| 59 | + public int solution(int n, int[][] wires) { |
| 60 | + init(n, wires); |
| 61 | + sol(); |
| 62 | + return ans; |
| 63 | + } |
| 64 | + |
| 65 | +} |
| 66 | +``` |
0 commit comments