티스토리 뷰

알고리즘/백준(BOJ)

백준 - 11657 타임머신

시나모온 2020. 6. 16. 21:13

문제 링크입니다 : https://www.acmicpc.net/problem/11657

 

11657번: 타임머신

첫째 줄에 도시의 개수 N (1 ≤ N ≤ 500), 버스 노선의 개수 M (1 ≤ M ≤ 6,000)이 주어진다. 둘째 줄부터 M개의 줄에는 버스 노선의 정보 A, B, C (1 ≤ A, B ≤ N, -10,000 ≤ C ≤ 10,000)가 주어진다. 

www.acmicpc.net

 

 

 

 

 

 

 

 

#include <iostream>
#include <vector>
#define INF 987654321
using namespace std;


int N, M;
vector<pair<int, pair<int, int>>> edge;
vector<int> dist;

bool bellmanFord(int start) {
    dist.assign(N + 1, INF);
	dist[start] = 0;
    
    // 모든 간선을 살펴본다.
    for (int i = 1; i < N; i++) {
        for (int j = 0; j < edge.size(); j++) {
            int here = edge[j].first;
            int next = edge[j].second.first;
            int distance = edge[j].second.second;
            if(dist[here] == INF) continue;
            if (dist[next] > dist[here] + distance) {
                dist[next] = dist[here] + distance;
            }
        }
    }

    for (int i = 0; i < edge.size(); i++) {
        int here = edge[i].first;
        int next = edge[i].second.first;
        int distance = edge[i].second.second;
        if(dist[here] == INF) continue;
        if (dist[next] > dist[here] + distance) {
            return false;
        }
    }

    return true;
}

int main() {
    int A, B, C;
    cin >> N >> M;

    edge.assign(M, pair<int, pair<int, int>>());

    for(int i = 0; i < M; i++) {
        cin >> A >> B >> C;
        edge[i] = {A, {B, C}};
    }

    if(bellmanFord(1)) {
        
        for(int i = 2; i <= N; i++) {
            if(dist[i] == INF) cout << -1 << '\n';
            else cout << dist[i] << '\n';
        }

    } else {
        cout << -1;
    }


    return 0;
}

 

 

 

개발 환경 : vscode

지적, 조언, 질문 환영입니다! 댓글 남겨주세요~

 

'알고리즘 > 백준(BOJ)' 카테고리의 다른 글

백준 - 3568 iSharp  (0) 2020.06.21
백준 - 1174 줄어드는 숫자  (0) 2020.06.16
백준 - 9370 미확인 도착지  (0) 2020.06.12
백준 - 1504 특정한 최단 경로  (0) 2020.06.12
백준 - 1753 최단경로  (0) 2020.06.12
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/04   »
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
글 보관함