반응형

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

 

14284번: 간선 이어가기 2

정점 n개, 0개의 간선으로 이루어진 무방향 그래프가 주어진다. 그리고 m개의 가중치 간선의 정보가 있는 간선리스트가 주어진다. 간선리스트에 있는 간선 하나씩 그래프에 추가해 나갈 것이다.

www.acmicpc.net

 

 

[ 문제풀이 ]

 

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

 

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
52
53
#include<iostream>
#include<vector>
#include<queue>
 
using namespace std;
 
int n, m, s, t;
vector<pair<intint>> list[5001];
int visited[5001];
 
int main()
{
    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 });
    }
 
    scanf("%d %d"&s, &t);
 
    priority_queue<pair<intint>vector<pair<intint>>, greater<pair<intint>>> pq;
 
    pq.push({ 0,s });
 
    while (!pq.empty()) {
        const int cur = pq.top().second;
        const int dist = pq.top().first;
        pq.pop();
 
        if (cur == t) {
            printf("%d", dist);
            return 0;
        }
 
        if (visited[cur] < dist) continue;
        visited[cur] = dist;
 
        for (auto& next : list[cur]) {
            const int nextNode = next.first;
            const int nextDist = next.second;
 
            if (visited[nextNode] > dist + nextDist) {
                visited[nextNode] = dist + nextDist;
                pq.push({ visited[nextNode], nextNode });
            }
        }
    }
}
cs
반응형

+ Recent posts