From fbc5f3573a6470d89fbe5d877efe6efdac6a249e Mon Sep 17 00:00:00 2001 From: Jinyeong Seol Date: Fri, 20 Jun 2025 23:31:22 +0900 Subject: [PATCH] =?UTF-8?q?[20250620]=20BOJ=20/=20G4=20/=20=EC=B9=9C?= =?UTF-8?q?=EA=B5=AC=EB=B9=84=20/=20=EC=84=A4=EC=A7=84=EC=98=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...4 \354\271\234\352\265\254\353\271\204.md" | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 "Seol-JY/202506/20 BOJ G4 \354\271\234\352\265\254\353\271\204.md" diff --git "a/Seol-JY/202506/20 BOJ G4 \354\271\234\352\265\254\353\271\204.md" "b/Seol-JY/202506/20 BOJ G4 \354\271\234\352\265\254\353\271\204.md" new file mode 100644 index 00000000..f12b60c3 --- /dev/null +++ "b/Seol-JY/202506/20 BOJ G4 \354\271\234\352\265\254\353\271\204.md" @@ -0,0 +1,78 @@ +```java +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.*; + +public class Main { + static int N, M, K; + static int[] prices; + static int[] parent; + static int[] minCost; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + N = nextInt(st); + M = nextInt(st); + K = nextInt(st); + + prices = new int[N + 1]; + parent = new int[N + 1]; + minCost = new int[N + 1]; + + st = new StringTokenizer(br.readLine()); + for (int i = 1; i <= N; i++) { + prices[i] = nextInt(st); + parent[i] = i; + minCost[i] = prices[i]; + } + + for (int i = 0; i < M; i++) { + st = new StringTokenizer(br.readLine()); + union(nextInt(st), nextInt(st)); + } + + for (int i = 1; i <= N; i++) { + int root = find(i); + minCost[root] = Math.min(minCost[root], prices[i]); + } + + int totalCost = 0; + boolean[] visited = new boolean[N + 1]; + + for (int i = 1; i <= N; i++) { + int root = find(i); + if (!visited[root]) { + visited[root] = true; + totalCost += minCost[root]; + } + } + if (totalCost <= K) { + System.out.println(totalCost); + } else { + System.out.println("Oh no"); + } + } + + private static int find(int x) { + if (parent[x] != x) { + parent[x] = find(parent[x]); + } + + return parent[x]; + } + + private static void union(int x, int y) { + int rootX = find(x); + int rootY = find(y); + if (rootX != rootY) { + parent[rootY] = rootX; + } + } + + private static int nextInt(StringTokenizer st) { + return Integer.parseInt(st.nextToken()); + } +} +```