|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + |
| 7 | + static int N, M, K; |
| 8 | + static int[] cost; |
| 9 | + static List<Integer>[] graph; |
| 10 | + static boolean[] visited; |
| 11 | + |
| 12 | + public static void main(String[] args) throws Exception { |
| 13 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 14 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 15 | + |
| 16 | + N = Integer.parseInt(st.nextToken()); |
| 17 | + M = Integer.parseInt(st.nextToken()); |
| 18 | + K = Integer.parseInt(st.nextToken()); |
| 19 | + |
| 20 | + cost = new int[N + 1]; |
| 21 | + visited = new boolean[N + 1]; |
| 22 | + graph = new ArrayList[N + 1]; |
| 23 | + |
| 24 | + for (int i = 1; i <= N; i++) graph[i] = new ArrayList<>(); |
| 25 | + |
| 26 | + st = new StringTokenizer(br.readLine()); |
| 27 | + for (int i = 1; i <= N; i++) { |
| 28 | + cost[i] = Integer.parseInt(st.nextToken()); |
| 29 | + } |
| 30 | + |
| 31 | + for (int i = 0; i < M; i++) { |
| 32 | + st = new StringTokenizer(br.readLine()); |
| 33 | + int a = Integer.parseInt(st.nextToken()); |
| 34 | + int b = Integer.parseInt(st.nextToken()); |
| 35 | + graph[a].add(b); |
| 36 | + graph[b].add(a); |
| 37 | + } |
| 38 | + |
| 39 | + int totalCost = 0; |
| 40 | + |
| 41 | + for (int i = 1; i <= N; i++) { |
| 42 | + if (!visited[i]) { |
| 43 | + int minCost = bfs(i); |
| 44 | + totalCost += minCost; |
| 45 | + |
| 46 | + if (totalCost > K) { |
| 47 | + System.out.println("Oh no"); |
| 48 | + return; |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + System.out.println(totalCost); |
| 54 | + } |
| 55 | + |
| 56 | + static int bfs(int start) { |
| 57 | + Queue<Integer> q = new ArrayDeque<>(); |
| 58 | + q.add(start); |
| 59 | + visited[start] = true; |
| 60 | + |
| 61 | + int minCost = cost[start]; |
| 62 | + |
| 63 | + while (!q.isEmpty()) { |
| 64 | + int cur = q.poll(); |
| 65 | + minCost = Math.min(minCost, cost[cur]); |
| 66 | + |
| 67 | + for (int next : graph[cur]) { |
| 68 | + if (!visited[next]) { |
| 69 | + visited[next] = true; |
| 70 | + q.offer(next); |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + return minCost; |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +``` |
0 commit comments