Skip to content

Commit 5e4ca76

Browse files
authored
Merge pull request #375 from AlgorithmWithGod/Seol-JY
[20250620] BOJ / G4 / 친구비 / 설진영
2 parents 7e13976 + fbc5f35 commit 5e4ca76

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
```java
2+
import java.io.BufferedReader;
3+
import java.io.IOException;
4+
import java.io.InputStreamReader;
5+
import java.util.*;
6+
7+
public class Main {
8+
static int N, M, K;
9+
static int[] prices;
10+
static int[] parent;
11+
static int[] minCost;
12+
13+
public static void main(String[] args) throws IOException {
14+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
15+
StringTokenizer st = new StringTokenizer(br.readLine());
16+
N = nextInt(st);
17+
M = nextInt(st);
18+
K = nextInt(st);
19+
20+
prices = new int[N + 1];
21+
parent = new int[N + 1];
22+
minCost = new int[N + 1];
23+
24+
st = new StringTokenizer(br.readLine());
25+
for (int i = 1; i <= N; i++) {
26+
prices[i] = nextInt(st);
27+
parent[i] = i;
28+
minCost[i] = prices[i];
29+
}
30+
31+
for (int i = 0; i < M; i++) {
32+
st = new StringTokenizer(br.readLine());
33+
union(nextInt(st), nextInt(st));
34+
}
35+
36+
for (int i = 1; i <= N; i++) {
37+
int root = find(i);
38+
minCost[root] = Math.min(minCost[root], prices[i]);
39+
}
40+
41+
int totalCost = 0;
42+
boolean[] visited = new boolean[N + 1];
43+
44+
for (int i = 1; i <= N; i++) {
45+
int root = find(i);
46+
if (!visited[root]) {
47+
visited[root] = true;
48+
totalCost += minCost[root];
49+
}
50+
}
51+
if (totalCost <= K) {
52+
System.out.println(totalCost);
53+
} else {
54+
System.out.println("Oh no");
55+
}
56+
}
57+
58+
private static int find(int x) {
59+
if (parent[x] != x) {
60+
parent[x] = find(parent[x]);
61+
}
62+
63+
return parent[x];
64+
}
65+
66+
private static void union(int x, int y) {
67+
int rootX = find(x);
68+
int rootY = find(y);
69+
if (rootX != rootY) {
70+
parent[rootY] = rootX;
71+
}
72+
}
73+
74+
private static int nextInt(StringTokenizer st) {
75+
return Integer.parseInt(st.nextToken());
76+
}
77+
}
78+
```

0 commit comments

Comments
 (0)