File tree Expand file tree Collapse file tree 1 file changed +79
-0
lines changed
Expand file tree Collapse file tree 1 file changed +79
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` java
2+ import java.io.* ;
3+ import java.util.* ;
4+
5+ class Solution {
6+ static int nodeCnt, answer;
7+ static Node [] nodes;
8+
9+ static class Node {
10+ int num;
11+ boolean isOn = false ;
12+ Node parent = null ;
13+ HashSet<Node > to = new HashSet<> ();
14+
15+ public Node (int num ){
16+ this . num = num;
17+ }
18+ }
19+
20+ public int solution (int n , int [][] lighthouse ) {
21+ nodeCnt = n;
22+ answer = 0 ;
23+ init(lighthouse);
24+
25+ makeTree(1 );
26+ turnLight(1 );
27+ for (int i = 1 ; i<= nodeCnt; i++ ){
28+ if (nodes[i]. isOn)answer++ ;
29+ }
30+ answer = Math . min(answer, nodeCnt - answer);
31+
32+ return answer;
33+ }
34+
35+ private void turnLight (int nodeNum ){
36+ Node node = nodes[nodeNum];
37+ if (node. to. size() == 0 ){
38+ node. isOn = false ;
39+ return ;
40+ }
41+
42+ boolean result = true ;
43+ for (Node child: node. to){
44+ turnLight(child. num);
45+ result &= child. isOn;
46+ }
47+ node. isOn = ! result;
48+ }
49+
50+ private void makeTree (int nodeNum ){
51+ Node node = nodes[nodeNum];
52+ for (Node child: node. to){
53+ child. parent = node;
54+ child. to. remove(node);
55+ makeTree(child. num);
56+ }
57+
58+ }
59+
60+ private void init (int [][] lighthouse ){
61+
62+ nodes = new Node [nodeCnt+ 1 ];
63+ for (int i = 0 ; i <= nodeCnt; i++ ){
64+ nodes[i] = new Node (i);
65+ }
66+
67+ for (int i = 0 ; i< nodeCnt- 1 ; i++ ){
68+ int n1 = lighthouse[i][0 ];
69+ int n2 = lighthouse[i][1 ];
70+
71+ Node node1 = nodes[n1];
72+ Node node2 = nodes[n2];
73+ node1. to. add(node2);
74+ node2. to. add(node1);
75+
76+ }
77+ }
78+ }
79+ ```
You can’t perform that action at this time.
0 commit comments