Baekjoon

[#11657] 타임머신

강람이 2020. 4. 1. 20:09
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
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <vector>
#include <limits.h>
#include <algorithm>
#include <queue>
 
using namespace std;
 
int main() {
    int n, m;
    scanf("%d %d"&n, &m);
 
    vector<vector<pair<intint>>> adj(n + 1);
    for (int i = 0; i < m; i++) {
        int a, b, c;
        scanf("%d %d %d"&a, &b, &c);
 
        adj[a].push_back(make_pair(b, c));
    }
 
    vector<int> dist(n + 1, INT_MAX);
    dist[1= 0;
 
    bool hasMinusCycle = false;
    for (int i = 1; i <= n; i++) {  
        //최단 경로의 최대갈이는 n-1이므로 n-1번. 근데 음의 사이클 판별을 위해 n번
        //i번째 루프: 시작점으로부터 각 정점까지 i개의 간선을 거쳐가는 최단거리를 갱신하자
        for (int j = 1; j <= n; j++) {  //모든 정점에 대해
            if (dist[j] != INT_MAX) {  //갱신된적 있는 노드인 경우에만
                for (int k = 0; k < adj[j].size(); k++) {
                    int there = adj[j][k].first;
                    int w = adj[j][k].second;
 
                    if (dist[there] > dist[j] + w) {
                        dist[there] = dist[j] + w;
 
                        if (i == n)  //i가 n번짼데 갱신이 된다면 음의 사이클 있다는 소리임
                            hasMinusCycle = true;
                    }
                }
            }
        }
    }
 
    if (hasMinusCycle)
        printf("-1\n");
    else {
        for (int i = 2; i <= n; i++) {
            if(dist[i]==INT_MAX)
                printf("-1\n");
            else
                printf("%d\n", dist[i]);
        }
    }
    return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

음의 가중치가 있으므로 벨만-포드 알고리즘

참고한 블로그: https://m.blog.naver.com/kks227/220796963742

 

벨만 포드 알고리즘(Bellman-Ford Algorithm) (수정: 2019-08-08)

이어서 소개해드릴 것은 또다른 최단경로 알고리즘입니다.벨만 포드 알고리즘(Bellman-Ford algorithm)인...

blog.naver.com