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

github : https://github.com/junho0956/Algorithm/blob/master/1753/1753/%EC%86%8C%EC%8A%A4.cpp

 

한 정점에서 다른 모든 정점으로의 최단거리를 구하려면

다익스트라의 개념을 활용해야 합니다.

일반적으로 구현하면N^2의 복잡도가 필요하기 때문에 우선순위 큐를 사용하여 NlogN 에 구현하였습니다.

 

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
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
#define INF 987654321
typedef pair<intint> pii;
 
int vertex, edge;
vector<pii> v[20001];
priority_queue<pii, vector<pii>, greater<pii> > q;
int dist[20001];
bool visit[20001];
 
void dijkstra(int start) {
    for (int i = 1; i <= vertex; i++) dist[i] = INF;
    dist[start] = 0;
    q.push({ 0,start });
 
    while (!q.empty()) {
        int w = q.top().first;
        int node = q.top().second;
        q.pop();
 
        if (visit[node]) continue;
        visit[node] = true;
 
        for (int i = 0; i < v[node].size(); i++) {
            int cur = v[node][i].first;
            int weight = v[node][i].second;
            if (!visit[cur] && dist[cur] > w + weight) {
                dist[cur] = w + weight;
                q.push({ w + weight, cur });
            }
        }
    }
}
 
int main() {
    ios::sync_with_stdio(0), cin.tie(0);
    
    int start_vertex;
    cin >> vertex >> edge >> start_vertex;
    for (int i = 0; i < edge; i++) {
        int s, e, w;
        cin >> s >> e >> w;
        v[s].push_back({ e,w });
    }
 
    dijkstra(start_vertex);
 
    for (int i = 1; i <= vertex; i++) {
        if (dist[i] == INF) cout << "INF\n";
        else cout << dist[i] << "\n";
    }
 
    return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

'algorithm > BOJ' 카테고리의 다른 글

BOJ 1238 파티  (0) 2020.02.23
BOJ 1916번 최소비용 구하기  (0) 2020.02.23
BOJ 2294번 동전 2  (0) 2020.02.21
BOJ 10835번 카드게임  (0) 2020.02.21
BOJ 10995번 별 찍기 - 20  (0) 2020.02.21

+ Recent posts