-
Notifications
You must be signed in to change notification settings - Fork 0
/
16562(Union Find)
74 lines (62 loc) · 1.9 KB
/
16562(Union Find)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.util.*;
import java.io.*;
public class Main {
static int money[], parent[];
static int N, M, K;
public static void union(int a, int b) {
int parenta = find(a);
int parentb = find(b);
if(parenta != parentb) {
if(parenta < parentb) {
parent[parentb] = parenta;
}else{
parent[parenta] = parentb;
}
}
}
public static int find(int a) {
if(parent[a] == a) {
return a;
}else{
return find(parent[a]);
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
K = Integer.parseInt(st.nextToken());
money = new int[N + 1];
parent = new int[N + 1];
st = new StringTokenizer(br.readLine());
for(int i = 1; i < N + 1; i++) {
money[i] = Integer.parseInt(st.nextToken());
parent[i] = i;
}
for(int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
int v = Integer.parseInt(st.nextToken());
int w = Integer.parseInt(st.nextToken());
union(v, w);
}
int result = 0;
for(int i = 1; i < N + 1; i++) {
int min = Integer.MAX_VALUE;
for(int j = 1; j < N + 1; j++) {
if(find(j) == i) {
min = Math.min(min, money[j]);
}
}
if(min != Integer.MAX_VALUE) {
result += min;
}
}
if(result <= K){
System.out.println(result);
}else{
System.out.println("Oh no");
}
}
}