Skip to content

Commit f8cea89

Browse files
authored
[20250415] BOJ / P5 / 개미 / 신희을
1 parent 793288a commit f8cea89

File tree

1 file changed

+127
-0
lines changed

1 file changed

+127
-0
lines changed
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
```java
2+
import java.util.*;
3+
4+
public class Main {
5+
6+
static int N;
7+
static int logN;
8+
static Node[][] parents;
9+
10+
static int[] ants;
11+
12+
static ArrayList<Node>[] lists;
13+
14+
public static void main(String[] args) throws Exception {
15+
16+
N = read();
17+
18+
ants = new int[N + 1];
19+
logN = (int) (Math.log(N) / Math.log(2));
20+
21+
lists = new ArrayList[N + 1];
22+
23+
24+
parents = new Node[N + 1][logN + 1];
25+
for(int i = 1; i <= N; i++) {
26+
lists[i] = new ArrayList<>();
27+
ants[i] = read();
28+
}
29+
30+
31+
for(int i = 1; i < N; i++) {
32+
int a = read();
33+
int b = read();
34+
int c = read();
35+
36+
lists[a].add(new Node(b, c));
37+
lists[b].add(new Node(a, c));
38+
}
39+
40+
dfs(1, 0);
41+
parents[1][0] = new Node(0,0);
42+
// for(int i = 1; i <= N; i++) {
43+
// System.out.println(parents[i][0].index);
44+
// }
45+
46+
for(int i = 1; i <= logN; i++) {
47+
for(int j = 1; j <= N; j++) {
48+
Node parent = parents[j][i-1];
49+
if(parent == null) continue;
50+
51+
Node node = parents[parent.index][i-1];
52+
53+
if(node == null) continue;
54+
55+
parents[j][i] = new Node(node.index, parent.value + node.value);
56+
}
57+
}
58+
59+
60+
StringBuilder sb = new StringBuilder();
61+
for(int i = 1; i <= N; i++) {
62+
int ant = ants[i];
63+
int room = i;
64+
for(int j = logN; j >= 0; j--) {
65+
if(parents[room][j] == null) continue;
66+
67+
if(parents[room][j].value > ant) continue;
68+
69+
ant -= parents[room][j].value;
70+
room = parents[room][j].index;
71+
72+
}
73+
74+
sb.append(room == 0 ? 1 : room).append("\n");
75+
}
76+
77+
System.out.println(sb);
78+
79+
80+
}
81+
82+
public static void dfs(int node, int parent) {
83+
84+
for(Node n : lists[node]) {
85+
if(n.index == parent) continue;
86+
parents[n.index][0] = new Node(node, n.value);
87+
dfs(n.index, node);
88+
}
89+
90+
}
91+
92+
private static class Node {
93+
int index;
94+
int value;
95+
96+
public Node(int parent, int value) {
97+
this.index = parent;
98+
this.value = value;
99+
}
100+
}
101+
102+
103+
104+
private static int read() throws Exception {
105+
int c;
106+
int n = 0;
107+
boolean negative = false;
108+
109+
while ((c = System.in.read()) <= 32) {
110+
if (c == -1) return -1;
111+
}
112+
113+
if (c == '-') {
114+
negative = true;
115+
c = System.in.read();
116+
}
117+
118+
do {
119+
n = n * 10 + (c - '0');
120+
c = System.in.read();
121+
} while (c > 32);
122+
123+
return negative ? -n : n;
124+
}
125+
}
126+
127+
```

0 commit comments

Comments
 (0)