반응형

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

 

1922번: 네트워크 연결

이 경우에 1-3, 2-3, 3-4, 4-5, 4-6을 연결하면 주어진 output이 나오게 된다.

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. pq에 출발점, 도착점과 거리를 넣습니다.

 

2. pq에서 하나씩 뽑아서 크루스칼 알고리즘을 통해  MST를 찾고, ans에 dist를 더해줍니다.

 

3. 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
#include<iostream>
#include<queue>
 
using namespace std;
 
int N, M;
int vect[1001];
 
struct node {
    int a;
    int b;
    int dist;
};
 
struct cmp {
    bool operator()(node right, node left) {
        return left.dist < right.dist;
    }
};
 
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"&N, &M);
    priority_queue<node, vector<node>, cmp> pq;
 
    for (int i = 1; i <= N; i++) {
        vect[i] = i;
    }
 
    for (int i = 0; i < M; i++) {
        int a, b, c;
        scanf("%d %d %d"&a, &b, &c);
        pq.push({ a,b,c });
    }
 
    int ans = 0;
 
    while (!pq.empty()) {
        const int a = pq.top().a;
        const int b = pq.top().b;
        const int dist = pq.top().dist;
        pq.pop();
 
        if (Find(a) != Find(b)) {
            Union(a, b);
            ans += dist;
        }
    }
 
    printf("%d", ans);
}
cs
반응형

+ Recent posts