https://www.acmicpc.net/problem/11657
dist
배열을 선언int
범위를 초과할 수 있음. 따라서 long
타입으로 정의import static java.lang.Integer.parseInt;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
public class Main {
static long[] dist;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = parseInt(st.nextToken());
int M = parseInt(st.nextToken());
dist = new long[N + 1];
Arrays.fill(dist, Long.MAX_VALUE);
dist[1] = 0;
List<Edge> edges = new ArrayList<>();
while (M-- > 0) {
st = new StringTokenizer(br.readLine());
int u = parseInt(st.nextToken());
int v = parseInt(st.nextToken());
int w = parseInt(st.nextToken());
edges.add(new Edge(u, v, w));
}
for (int i = 0; i < N - 1; i++) {
for (Edge edge : edges) {
if (dist[edge.u] != Long.MAX_VALUE && dist[edge.u] + edge.w < dist[edge.v]) {
dist[edge.v] = dist[edge.u] + edge.w;
}
}
}
for (Edge edge : edges) {
if (dist[edge.u] != Long.MAX_VALUE && dist[edge.u] + edge.w < dist[edge.v]) {
System.out.println(-1);
System.exit(0);
}
}
List<String> answer = new ArrayList<>();
for (int i = 2; i < dist.length; i++) {
long value = dist[i] == Long.MAX_VALUE ? -1 : dist[i];
answer.add(String.valueOf(value));
}
System.out.print(answer.stream().collect(Collectors.joining("\n")));
br.close();
}
static class Edge {
int u, v, w;
public Edge(int u, int v, int w) {
this.u = u;
this.v = v;
this.w = w;
}
}
}