반응형

https://www.acmicpc.net/problem/10423

 

10423번: 전기가 부족해

첫째 줄에는 도시의 개수 N(1 ≤ N ≤ 1,000)과 설치 가능한 케이블의 수 M(1 ≤ M ≤ 100,000)개, 발전소의 개수 K(1 ≤ K ≤ N)개가 주어진다. 둘째 줄에는 발전소가 설치된 도시의 번호가 주어진다. 셋째

www.acmicpc.net

 

 

[ 문제풀이 ]

1. vect 배열을 만들고 vect [ i ] = i로 초기화해 줍니다.

 

2. 발전소가 설치된 노드를 입력받고, vect [ plant ] = 0으로 초기화합니다.

 

3. node struct를 만들고, node arr [ 100001 ] 배열을 만들어 각각의 u, v, w를 저장합니다.

 

4. arr 배열을 w를 기준으로 오름차순으로 정렬합니다.

 

5. for문을 돌며 Union-Find를 이용하여 각 노드들을 이어주고, ans에 비용을 저장해 줍니다.

 

6. ans를 출력합니다.

 

[ 소스코드 ]

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
#include<iostream>
#include<algorithm>
 
using namespace std;
 
struct node {
    int u;
    int v;
    int w;
};
 
struct cmp {
    bool operator()(node left, node right) {
        return left.w < right.w;
    }
};
 
int N, M, K;
int vect[1001];
node arr[100001];
 
int Find(int num) 
{
    if (vect[num] == num) return num;
    return vect[num] = Find(vect[num]);
}
 
void Union(int a, int b)
{
    int pa = Find(a);
    int pb = Find(b);
 
    vect[pb] = pa;
}
 
int main()
{
    scanf("%d %d %d"&N, &M, &K);
 
    for (int i = 1; i <= N; i++) {
        vect[i] = i;
    }
 
    for (int i = 0; i < K; i++) {
        int plant;
        scanf("%d"&plant);
        vect[plant] = 0;
    }
 
    for (int i = 0; i < M; i++) {
        scanf("%d %d %d"&arr[i].u, &arr[i].v, &arr[i].w);
    }
 
    sort(arr, arr + M, cmp());
 
    int ans = 0;
 
    for(int i=0;i<M;i++){
        const int u = arr[i].u;
        const int v = arr[i].v;
        const int w = arr[i].w;
 
        if (Find(u) != Find(v)) {
            Union(u, v);
            ans += w;
        }
    }
 
    printf("%d", ans);
}
cs
반응형

'백준' 카테고리의 다른 글

[ 백준 ] 1368번 - 물대기 (C++)  (0) 2023.02.04
[ 백준 ] 1261번 - 알고스팟 (C++)  (0) 2023.02.03
[ 백준 ] 5214번 - 환승 (C++)  (0) 2023.02.01
[ 백준 ] 1584번 - 게임 (C++)  (0) 2023.01.31
[ 백준 ] 1175번 - 배달 (C++)  (0) 2023.01.30

+ Recent posts