알고리즘/BOJ

[백준] 16562 친구비

세진짱 2020. 1. 30. 11:37

 

유니온 파인드를 이용하는 기본문제다

친구면 비용이 작은 사람들에게 합쳐준다!

 

마지막으로 내가 0이라고 생각하고 1~n까지 merge해주면서 비용을 합쳐주면 된다!

 

소스코드

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
#include <iostream>
#include <algorithm>
using namespace std;
int n, m, k;
int arr[10010];
int p[10010];
 
int find(int x) {
    if (p[x] == x) return x;
    return p[x] = find(p[x]);
}
 
void merge(int x, int y) {
    x = find(x);
    y = find(y);
    if (x == y) return;
    if (arr[x] > arr[y]) p[x] = y;
    else p[y] = x;
}
 
 
int main() {
    scanf(" %d %d %d"&n, &m, &k);
    for (int i = 1; i <= n; i++) p[i] = i;
    for (int i = 1; i <= n; i++scanf(" %d"&arr[i]);
    for (int i = 0; i < m; i++) {
        int u, v; scanf(" %d %d"&u, &v);
        if (find(u) != find(v)) merge(find(u), find(v));
    }
    int ans = 0;
    for (int i = 1; i <= n; i++) {
        if (find(i) != 0) {
            ans += arr[find(i)];
            merge(0, find(i));
        }
    }
    if (ans <= k) printf("%d\n", ans);
    else puts("Oh no");
}