Skip to content

Commit aca3c0c

Browse files
authored
Merge pull request #1223 from AlgorithmWithGod/0224LJH
[20251025] PGM / Lv3 / 등대 / 이종환
2 parents 6207cdb + 0b39e0e commit aca3c0c

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

0224LJH/202510/25 PGM 등대.md

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
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+
```

0 commit comments

Comments
 (0)