본문 바로가기
코딩 문제 풀이/백준

[백준] 자바 문제 풀이 16562 : 골드4

by 코딩하는 랄로 2023. 9. 20.
728x90
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;

public class Main {
	static int[] parent;

	public static boolean union(int x, int y) {
		x = find(x);
		y = find(y);
		if (x == y)
			return false;
		if (x <= y)
			parent[y] = x;
		else
			parent[x] = y;
		return true;
	}

	public static int find(int x) {
		if (parent[x] == x)
			return x;
		return find(parent[x]);
	}

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer str = new StringTokenizer(br.readLine(), " ");
		
		int n = Integer.parseInt(str.nextToken());
		int m = Integer.parseInt(str.nextToken());
		int cost = Integer.parseInt(str.nextToken());
		
		int[] clist = new int[n];
		str = new StringTokenizer(br.readLine(), " ");
		for(int i = 0; i < n; i++)
			clist[i] = Integer.parseInt(str.nextToken());
		
		parent = new int[n];
		for(int i = 0; i < n; i++) parent[i] = i;
		
		for(int i = 0; i < m; i++) {
			str = new StringTokenizer(br.readLine(), " ");
			union(Integer.parseInt(str.nextToken())-1, Integer.parseInt(str.nextToken())-1);
		}
		HashMap<Integer, Integer> map = new HashMap<>();
		for(int i = 0; i < n; i++) {
			int root = find(i);
			if(map.containsKey(root)){
				if(map.get(root) > clist[i]) {
					map.put(root, clist[i]);
				}
			}
			else {
				map.put(root, clist[i]);
			}
		}
		
		int total = 0;
		for(Integer key : map.keySet()) {
			total += map.get(key);
		}
		
		if(total <= cost)
			System.out.println(total);
		else
			System.out.println("Oh no");
	}
}
728x90