알고리즘/백준

[백준 5972] 택배 배송 C++

겜도리도리 2023. 3. 3. 23:28
반응형

문제

백준 5972 택배 배송 C++

 

5972번: 택배 배송

농부 현서는 농부 찬홍이에게 택배를 배달해줘야 합니다. 그리고 지금, 갈 준비를 하고 있습니다. 평화롭게 가려면 가는 길에 만나는 모든 소들에게 맛있는 여물을 줘야 합니다. 물론 현서는

www.acmicpc.net

풀이

문제 설명이 애매하게 되어있는데, 하나 이상의 길로 연결되어 있을 수 있다는 점이 거슬렸다.

시작, 끝 점은 똑같은데 비용이 다른 간선을 말한다기보다는 다른 점으로 우회하여 갈 수 있다고 받아들였다.

 

풀이는 일반적인 다익스트라 문제 해법을 사용해 해결해주면 된다.

우선 순위 큐를 사용하여 시작 점부터 간선 정보를 갱신해 주고, N까지 가는 비용을 출력한다.

소스 코드

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
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
 
const int MAX = 1987654321;
 
vector<pair<intint>> graph[50001];
bool visited[50001];
int dist[50001];
int N = 0;
int M = 0;
 
void Dijkstra(int start)
{
    priority_queue<pair<intint>> pq;
    pq.push(make_pair(0, start));
    dist[start] = 0;
 
    while (!pq.empty())
    {
        int cost = -pq.top().first;
        int cur = pq.top().second;
        pq.pop();
 
        if (visited[cur])
            continue;
 
        visited[cur] = true;
 
        for (size_t i = 0; i < graph[cur].size(); i++)
        {
            int nCost = cost + graph[cur][i].first;
            int next = graph[cur][i].second;
 
            if (nCost < dist[next])
            {
                dist[next] = nCost;
                pq.push(make_pair(-dist[next], next));
            }
        }
    }
}
 
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
 
    int a = 0;
    int b = 0;
    int c = 0;
    cin >> N >> M;
 
    for (int i = 0; i <= N; i++)
    {
        dist[i] = MAX;
    }
 
    for (int i = 0; i < M; i++)
    {
        cin >> a >> b >> c;
        graph[a].push_back(make_pair(c, b));
        graph[b].push_back(make_pair(c, a));
    }
 
    Dijkstra(1);
    cout << dist[N];
 
    return 0;
}
cs
반응형

'알고리즘 > 백준' 카테고리의 다른 글

[백준 4811] 알약 C++  (0) 2023.05.15
[백준 2302] 극장 좌석 C++  (0) 2023.05.11
[백준 10025] 게으른 백곰 C++  (0) 2023.02.23
[백준 2473] 세 용액 C++  (10) 2023.02.20
[백준 2467] 용액 C++  (0) 2023.02.19