반응형

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

 

5972번: 택배 배송

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

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. dijkstra를 활용하여 1부터 N까지 이동합니다.

 

2. 이동거리를 출력합니다.

 

[ 소스코드 ]

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
#include<iostream>
#include<vector>
#include<queue>
 
using namespace std;
 
int N, M;
vector<pair<intint>> list[50001];
int visited[50001];
 
int main()
{
    priority_queue<pair<intint>vector<pair<intint>>, greater<pair<intint>>> pq;
    scanf("%d %d"&N, &M);
 
    fill(visited, visited + N + 1987654321);
 
    for (int i = 0; i < M; i++) {
        int A, B, C;
        scanf("%d %d %d"&A, &B, &C);
 
        list[A].push_back({ B,C });
        list[B].push_back({ A,C });
    }
 
    pq.push({ 0,1 });
 
    while (!pq.empty()) {
        const int cur = pq.top().second;
        const int dist = pq.top().first;
        pq.pop();
 
        if (cur == N) {
            printf("%d", dist);
            return 0;
        }
 
        if (visited[cur] < dist) continue;
        visited[cur] = dist;
 
        for (auto& next : list[cur]) {
            const int nNode = next.first;
            const int nDist = next.second;
 
            if (visited[nNode] > dist + nDist) {
                visited[nNode] = dist + nDist;
                pq.push({ visited[nNode], nNode });
            }
        }
    }
}
cs
반응형

+ Recent posts