본문 바로가기

공부합시다

다익스트라

조금 더 정리가 필요할 것 같다..

 

입력

첫 줄에 정점의 개수 N과 간선의 개수 M, 그리고 시작 정점 S가 주어집니다.
다음 M줄에 간선의 관계 시작정점 u와 도착정점 v 그리고 간선 가중치 w가 주어집니다.

7  11  1
1  2  4
1  3  10
1  7  20
2  3  4
2  4  3
3  5  7
4  3  11
5  7  4
6  5  1
7  6  10
6  4  2

 

출력

시작정점에서 각 정점사이의 거리를 모두 출력합니다.

0
4
8
7
15
29
19

 

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <functional>
#include <string>
#include <queue>
#include <deque>
#include <stack>
#include <set>
#include <map>
#include <cmath>
#include <cstring>
#include <bitset>
#include <stdio.h>

#define xx first
#define yy second
#define all(x) (x).begin(), (x).end()

using namespace std;
using i64 = long long int;
using ii = pair<int, int>;
using iis = pair<int, string>;
using ii64 = pair<i64, i64>;
using iii = tuple<int, int, int>;

int n, d;

vector<vector<ii>> edge;

vector<int> Dijkstra(int start) {
    vector<int> dist(n+1, -1);
    priority_queue<pair<int, int> > pq; // first : dist , second : vertex_pos
    
    dist[start] = 0;
    pq.push(make_pair(-dist[start], start)); // Min-Heap처럼 사용하기 위해 앞의 거리 인자에 -값을 곱해줌.
    while (!pq.empty()) {
        int here = pq.top().second;
        int heredist = -pq.top().first;
        
        pq.pop();
        if (heredist > dist[here]) 
            continue;
        for (int i = 0; i < edge[here].size(); i++) {
            int there = edge[here][i].first;
            int nextdist = heredist + edge[here][i].second;
            if (dist[there] == -1 || dist[there] > nextdist) { //최단 거리 갱신
                dist[there] = nextdist;
                pq.push(make_pair(-nextdist, there));
            }
        }
    }
    return dist;
}

int main() {
    int m, s;
    scanf("%d %d %d", &n, &m, &s);
    
    edge.resize(n + 1);
    for (int i = 0; i < m; i++) {
        int u, v;
        
        scanf("%d %d %d", &u, &v, &d);
        edge[u].push_back(make_pair(v, d));
    }
    
    vector<int> dist = Dijkstra(s);
    for (int i = 1; i <= n; i++) {
        cout << dist[i] << endl;
    }
    return 0;
}

'공부합시다' 카테고리의 다른 글

좌표압축 코드  (0) 2021.12.24
투포인터 예시 코드  (0) 2021.09.23
세그트리  (0) 2021.05.15
pbds  (0) 2021.05.08
LIS 최장 증가 부분 수열  (0) 2020.10.25