Skip to content

Commit 82dfae1

Browse files
authored
Merge pull request #447 from AlgorithmWithGod/lkhyun
[20250712] BOJ / G2 / 할로윈의 양아치 / 이강현
2 parents 3cbc409 + c6368ca commit 82dfae1

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
```java
2+
import java.util.*;
3+
import java.io.*;
4+
5+
public class Main{
6+
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
7+
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
8+
static StringTokenizer st;
9+
static int N,M,K;
10+
static int[] candies;
11+
static List<Integer>[] friends;
12+
static int[] dp;
13+
14+
public static void main(String[] args) throws Exception{
15+
st = new StringTokenizer(br.readLine());
16+
N = Integer.parseInt(st.nextToken());
17+
M = Integer.parseInt(st.nextToken());
18+
K = Integer.parseInt(st.nextToken());
19+
candies = new int[N+1];
20+
friends = new List[N+1];
21+
dp = new int[K];
22+
23+
st = new StringTokenizer(br.readLine());
24+
for (int i = 1; i <= N; i++) {
25+
candies[i] = Integer.parseInt(st.nextToken());
26+
friends[i] = new ArrayList<>();
27+
}
28+
29+
for (int i = 1; i <= M; i++) {
30+
st = new StringTokenizer(br.readLine());
31+
int u = Integer.parseInt(st.nextToken());
32+
int v = Integer.parseInt(st.nextToken());
33+
friends[u].add(v);
34+
friends[v].add(u);
35+
}
36+
37+
boolean[] visited = new boolean[N+1];
38+
for (int i = 1; i <= N; i++) {
39+
if(visited[i]) continue;
40+
int childCnt = 0;
41+
int candyCnt = 0;
42+
43+
ArrayDeque<Integer> q = new ArrayDeque<>();
44+
q.add(i);
45+
visited[i] = true;
46+
while (!q.isEmpty()) {
47+
int u = q.poll();
48+
childCnt++;
49+
candyCnt += candies[u];
50+
for (int v : friends[u]) {
51+
if(!visited[v]) {
52+
q.add(v);
53+
visited[v] = true;
54+
}
55+
}
56+
}
57+
58+
for (int j = K-1; j >= childCnt; j--) {
59+
dp[j] = Math.max(dp[j],dp[j-childCnt] + candyCnt);
60+
}
61+
}
62+
63+
int maxCnt = 0;
64+
for (int i = 0; i < K; i++) {
65+
maxCnt = Math.max(maxCnt, dp[i]);
66+
}
67+
bw.write(maxCnt + "");
68+
69+
bw.close();
70+
}
71+
}
72+
```

0 commit comments

Comments
 (0)