1+ import java .util .ArrayList ;
2+
3+ public class 전력망을_둘로_나누기 {
4+
5+ public static ArrayList <Integer >[] tree ;
6+ public static boolean [] isVisited ;
7+ public static int total , result ;
8+
9+ public static int solution (int n , int [][] wires ) {
10+
11+ result = Integer .MAX_VALUE ;
12+ tree = new ArrayList [n + 1 ];
13+ isVisited = new boolean [n + 1 ];
14+ total = n ;
15+
16+ for (int i = 1 ; i <= n ; i ++) {
17+ tree [i ] = new ArrayList <>();
18+ }
19+
20+ for (int [] wire : wires ) {
21+ tree [wire [0 ]].add (wire [1 ]);
22+ tree [wire [1 ]].add (wire [0 ]);
23+ }
24+
25+ search (1 );
26+
27+ return result ;
28+ }
29+
30+ public static int search (int num ) {
31+ isVisited [num ] = true ;
32+ int sum = 0 ;
33+ for (int node : tree [num ]) {
34+ if (!isVisited [node ]) {
35+ int cnt = search (node );
36+ // group1(total - cnt) - group2(cnt)
37+ result = Math .min (result , Math .abs (total - cnt * 2 ));
38+ sum += cnt ;
39+ }
40+ }
41+ return sum + 1 ;
42+ }
43+
44+
45+ public static void main (String [] args ) {
46+ System .out .println (solution (
47+ 9 ,
48+ new int [][]{{1 , 3 }, {2 , 3 }, {3 , 4 }, {4 , 5 }, {4 , 6 }, {4 , 7 }, {7 , 8 }, {7 , 9 }}
49+ ));
50+ System .out .println (solution (
51+ 4 ,
52+ new int [][]{{1 , 2 }, {2 , 3 }, {3 , 4 }}
53+ ));
54+ System .out .println (solution (
55+ 7 ,
56+ new int [][]{{1 , 2 }, {2 , 7 }, {3 , 7 }, {3 , 4 }, {4 , 5 }, {6 , 7 }}
57+ ));
58+ }
59+ }
0 commit comments