Skip to content

Commit 06a2ee5

Browse files
authored
Merge pull request #1820 from AlgorithmWithGod/Ukj0ng
[20260123] BOJ / G2 / 우수 마을 / 한종욱
2 parents 0f3ce27 + 3ae956b commit 06a2ee5

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
```
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
7+
private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
8+
private static List<Integer>[] graph;
9+
private static int[][] dp;
10+
private static int[] nodes;
11+
private static int N;
12+
13+
public static void main(String[] args) throws IOException {
14+
init();
15+
DFS(1, -1);
16+
17+
bw.write(Math.max(dp[1][0], dp[1][1]) + "\n");
18+
bw.flush();
19+
bw.close();
20+
br.close();
21+
}
22+
23+
private static void init() throws IOException {
24+
N = Integer.parseInt(br.readLine());
25+
StringTokenizer st = new StringTokenizer(br.readLine());
26+
27+
graph = new List[N+1];
28+
dp = new int[N+1][2];
29+
nodes = new int[N+1];
30+
31+
for (int i = 1; i <= N; i++) {
32+
graph[i] = new ArrayList<>();
33+
nodes[i] = Integer.parseInt(st.nextToken());
34+
}
35+
36+
for (int i = 0; i < N-1; i++) {
37+
st = new StringTokenizer(br.readLine());
38+
int U = Integer.parseInt(st.nextToken());
39+
int V = Integer.parseInt(st.nextToken());
40+
41+
graph[U].add(V);
42+
graph[V].add(U);
43+
}
44+
}
45+
46+
private static void DFS(int current, int parent) {
47+
dp[current][0] = nodes[current];
48+
dp[current][1] = 0;
49+
for (int next : graph[current]) {
50+
if (next == parent) continue;
51+
DFS(next, current);
52+
53+
dp[current][0] += dp[next][1];
54+
dp[current][1] += Math.max(dp[next][0], dp[next][1]);
55+
}
56+
}
57+
}
58+
```

0 commit comments

Comments
 (0)