본문 바로가기

BOJ 1753번 : 최단경로 본문

BOJ

BOJ 1753번 : 최단경로

00rigin 2022. 3. 30. 00:40

다익스트라 알고리즘을 사용하는 문제이다.

이상하게도... 빠른 입출력을 사용하지 않으면 런타임 에러가 뜬다...ㅠ

다익스트라 알고리즘은 아래 글을 보면 된다.

https://00rigin.tistory.com/54

 

다익스트라(Dijkstra) 알고리즘

다익스트라 알고리즘은 최단거리 (shortest path) 탐색 알고리즘의 일종으로, DP에 기반한 알고리즘이다. 한 node에서 다른 모든 node 까지의 최단거리를 탐색할 수 있다. 각 노드간 간선이 존재하고,

00rigin.tistory.com

 

<소스코드>

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
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
 
using namespace std;
 
void dijkstra(vector<vector<pair<int,int>>> map, vector<int> d, int start ){
    
    d[start] = 0;
    priority_queue<pair<int,int>> pq; // 거리, 노드
    
    pq.push(make_pair(0, start));
    
    while(!pq.empty()){
        int cur = pq.top().second;
        int dist = pq.top().first * -1;
        pq.pop();
        
        if(d[cur] < dist) continue;
        
        for(int i = 0; i<map[cur].size(); i++){
            int next = map[cur][i].first;
            int next_dis = map[cur][i].second + dist;
            
            if(d[next] > next_dis){
                d[next] = next_dis;
                pq.push(make_pair(d[next]*-1, next));
            }
        }
    }
    
    for(int i = 1; i<d.size(); i++){
        if(d[i] == INT_MAX)
            cout<<"INF"<<endl;
        
        else
            cout<<d[i]<<endl;
    }
}
 
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    
    
    int n,e,start;
    
    cin>>n>>e; // 노드 간선
    cin>>start;
    
    vector<vector<pair<int,int>>> map(n+1);
    vector<int> d(n+1,INT_MAX);
    
    for(int i = 0; i<e; i++){
        int u,v,w;
        cin>>u>>v>>w;
        map[u].push_back(make_pair(v, w));
    }
    
    dijkstra(map, d, start);
    
}
 
cs

<문제>

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

 

1753번: 최단경로

첫째 줄에 정점의 개수 V와 간선의 개수 E가 주어진다. (1 ≤ V ≤ 20,000, 1 ≤ E ≤ 300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘째 줄에는 시작 정점의 번호 K(1 ≤ K ≤ V)가

www.acmicpc.net

 

'BOJ' 카테고리의 다른 글

BOJ 11657번 : 타임머신  (0) 2022.04.05
BOJ 1504번 : 특정한 최단 경로  (0) 2022.04.02
BOJ 13975번 : 파일 합치기3  (0) 2022.03.26
BOJ 18352번 : 특정 거리의 도시 찾기  (0) 2022.03.18
BOJ 3986번 : 좋은 단어  (0) 2022.03.18
Comments