Skip to content

Commit db1ddae

Browse files
authored
Merge pull request #897 from AlgorithmWithGod/LiiNi-coder
[20250915] BOJ / G4 / 친구비 / 이인희
2 parents f84484c + f484007 commit db1ddae

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+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
public static void main(String[] args) throws IOException {
7+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
8+
StringTokenizer st = new StringTokenizer(br.readLine());
9+
int N = Integer.parseInt(st.nextToken());
10+
int M = Integer.parseInt(st.nextToken());
11+
int K = Integer.parseInt(st.nextToken());
12+
int[] parent = new int[N + 1];
13+
int[] cost = new int[N + 1];
14+
st = new StringTokenizer(br.readLine());
15+
for (int i = 1; i <= N; i++) {
16+
cost[i] = Integer.parseInt(st.nextToken());
17+
parent[i] = i;
18+
}
19+
for (int i = 0; i < M; i++) {
20+
st = new StringTokenizer(br.readLine());
21+
int a = Integer.parseInt(st.nextToken());
22+
int b = Integer.parseInt(st.nextToken());
23+
int pa = find(parent, a);
24+
int pb = find(parent, b);
25+
if (pa != pb) {
26+
if (cost[pa] < cost[pb])
27+
parent[pb] = pa;
28+
else
29+
parent[pa] = pb;
30+
}
31+
}
32+
33+
boolean[] visited = new boolean[N + 1];
34+
35+
int total = 0;
36+
for (int i = 1; i <= N; i++) {
37+
int p = find(parent, i);
38+
if (!visited[p]) {
39+
total += cost[p];
40+
visited[p] = true;
41+
}
42+
}
43+
44+
if (total <= K)
45+
System.out.println(total);
46+
else
47+
System.out.println("Oh no");
48+
}
49+
50+
static int find(int[] parent, int x) {
51+
if (parent[x] == x)
52+
return x;
53+
parent[x] = find(parent, parent[x]);
54+
return parent[x];
55+
}
56+
}
57+
58+
```

0 commit comments

Comments
 (0)