"""
BOJ 타임머신 문제 (https://www.acmicpc.net/problem/11657)
1<=N<=500
1<=M<=6000
1. 아이디어
- 모든 간선 확인
- 음의 간선 존재 => 벨만포드 알고리즘
2. 시간복잡도
- O(VE)
3. 자료구조
"""
import sys
input = sys.stdin.readline
N,M = map(int, input().split())
edges = [] #간선 테이블
INF = int(1e9)
distance = [INF]*(N+1) #최단 거리 테이블
for _ in range(M):
a, b, c = map(int, input().split())
edges.append((a,b,c))
def bellmanford(start):
distance[start]=0
for i in range(N):
for j in range(M): #매 반복마다 모든 간선 확인
cur = edges[j][0]
next = edges[j][1]
cost = edges[j][2]
if distance[cur] != INF and distance[next] > distance[cur] + cost: ###
distance[next] = distance[cur] + cost
if i==N-1:
return True
return False
negative_cycle = bellmanford(1)
if negative_cycle:
print("-1")
else:
for i in range(2, N+1):
if distance[i]==INF:
print("-1")
else:
print(distance[i])
참고 - 이코테 파이썬
'CS > Algorithm' 카테고리의 다른 글
[Algorithm][다익스트라] (0) | 2024.07.02 |
---|---|
[Algorithm] 이코테 : 두 배열의 원소 교체 (1) | 2024.06.30 |
[Algorithm] 선택정렬, 삽입정렬, 계수정렬 (0) | 2024.06.30 |
[Algorithm][이진탐색] 백준 1920 : 수찾기 (0) | 2024.06.29 |
[Algorithm][dfs, bfs] 백준 1260 : dfs와 bfs (0) | 2024.06.28 |