N개의 도시가 있다. 그리고 한 도시에서 출발하여 다른 도시에 도착하는 버스가 M개 있다. 각 버스는 A, B, C로 나타낼 수 있는데, A는 시작도시, B는 도착도시, C는 버스를 타고 이동하는데 걸리는 시간이다. 시간 C가 양수가 아닌 경우가 있다. C = 0인 경우는 순간 이동을 하는 경우, C < 0인 경우는 타임머신으로 시간을 되돌아가는 경우이다.
1번 도시에서 출발해서 나머지 도시로 가는 가장 빠른 시간을 구하는 프로그램을 작성하시오.
첫째 줄에 도시의 개수 N (1 ≤ N ≤ 500), 버스 노선의 개수 M (1 ≤ M ≤ 6,000)이 주어진다. 둘째 줄부터 M개의 줄에는 버스 노선의 정보 A, B, C (1 ≤ A, B ≤ N, -10,000 ≤ C ≤ 10,000)가 주어진다.
만약 1번 도시에서 출발해 어떤 도시로 가는 과정에서 시간을 무한히 오래 전으로 되돌릴 수 있다면 첫째 줄에 -1을 출력한다. 그렇지 않다면 N-1개 줄에 걸쳐 각 줄에 1번 도시에서 출발해 2번 도시, 3번 도시, ..., N번 도시로 가는 가장 빠른 시간을 순서대로 출력한다. 만약 해당 도시로 가는 경로가 없다면 대신 -1을 출력한다.
for (int i = 0; i < M; i++) {
input = br.readLine().split(" ");
from = Integer.parseInt(input[0]);
to = Integer.parseInt(input[1]);
weight = Integer.parseInt(input[2]);
adjlist[from].add(new Edge(to, weight));
}
long[] dist = new long[N + 1];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[1] = 0;
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
for (Edge edge : adjlist[j]) {
if (dist[j] != Integer.MAX_VALUE && dist[edge.to] > dist[j] + edge.weight) {
dist[edge.to] = dist[j] + edge.weight;
if (i == N) {
System.out.println(-1);
return;
}
}
}
}
}
StringBuilder sb = new StringBuilder();
for (int i = 2; i <= N; i++) {
if (dist[i] == Integer.MAX_VALUE)
sb.append(-1).append('\n');
else
sb.append(dist[i]).append('\n');
}
System.out.print(sb.toString());
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
static int N, M;
static List<Edge>[] adjlist;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] input = br.readLine().split(" ");
N = Integer.parseInt(input[0]);
M = Integer.parseInt(input[1]);
adjlist = new List[N + 1];
for (int i = 1; i <= N; i++) {
adjlist[i] = new ArrayList<>();
}
int from, to, weight;
for (int i = 0; i < M; i++) {
input = br.readLine().split(" ");
from = Integer.parseInt(input[0]);
to = Integer.parseInt(input[1]);
weight = Integer.parseInt(input[2]);
adjlist[from].add(new Edge(to, weight));
}
bellmanford();
}
private static void bellmanford() {
long[] dist = new long[N + 1];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[1] = 0;
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
for (Edge edge : adjlist[j]) {
if (dist[j] != Integer.MAX_VALUE && dist[edge.to] > dist[j] + edge.weight) {
dist[edge.to] = dist[j] + edge.weight;
if (i == N) {
System.out.println(-1);
return;
}
}
}
}
}
StringBuilder sb = new StringBuilder();
for (int i = 2; i <= N; i++) {
if (dist[i] == Integer.MAX_VALUE)
sb.append(-1).append('\n');
else
sb.append(dist[i]).append('\n');
}
System.out.print(sb.toString());
}
static class Edge {
int to;
int weight;
public Edge(int to, int weight) {
this.to = to;
this.weight = weight;
}
}
}