코딩테스트/그래프|트리
[그래프(벨만 포드)] (CHECK) 백준 11657 타임머신 C++
유(YOO)
2022. 1. 27. 11:17
https://www.acmicpc.net/problem/11657
가중치 음수
#include <iostream>
#include <vector>
#define MAX 501
using namespace std;
int INF = 1000000000;
int n, m, a, b, c;
long long dp[MAX];
vector<int> v;
vector<pair<int, int>> adj[MAX];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n >> m;
for (int i = 0; i < m; i++) {
cin >> a >> b >> c;
adj[a].push_back({ b,c });
}
for (int i = 0; i <= n; i++) dp[i] = INF;
dp[1] = 0;
for (int k = 0; k < n; k++) {
for (int i = 1; i <= n; i++) {
for (int j = 0; j < adj[i].size(); j++) {
if (dp[i] == INF) continue;
if (dp[adj[i][j].first] > dp[i] + adj[i][j].second) {
dp[adj[i][j].first] = dp[i] + adj[i][j].second;
}
}
}
}
for (int i = 1; i <= n; i++) {
for (int j = 0; j < adj[i].size(); j++) {
if (dp[i] == INF) continue;
if (dp[adj[i][j].first] > dp[i] + adj[i][j].second) {
printf("-1\n");
return 0;
}
}
}
for (int i = 2; i <= n; i++) {
if (dp[i] == INF) printf("%d\n", -1);
else printf("%d\n", dp[i]);
}
return 0;
}