|
| 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