[Link] https://www.acmicpc.net/problem/11657
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
String[] line = getLine(br);
int n = toi(line[0]), m = toi(line[1]);
ArrayList<Edge> edges = new ArrayList<>();
boolean[] visit = new boolean[n];
long[] belfor = new long[n];
Arrays.fill(belfor, Integer.MAX_VALUE);
for(int i = 0; i < m; i++) {
line = getLine(br);
int a = toi(line[0]) - 1, b = toi(line[1]) - 1, c = toi(line[2]);
edges.add(new Edge(a, b, (long)c));
}
belfor[0] = 0l;
visit[0] = true;
for(int iter = 0; iter < n; iter++) {
for(Edge edge: edges) {
if(!visit[edge.from]) continue;
if(belfor[edge.from] + edge.dis < belfor[edge.to]) {
belfor[edge.to] = belfor[edge.from] + edge.dis;
visit[edge.to] = true;
}
}
}
for(Edge edge: edges) {
if(!visit[edge.from]) continue;
if(belfor[edge.from] + edge.dis < belfor[edge.to]) {
print(-1);
return;
}
}
for(int i = 1; i < n; i++) sb.append(visit[i] ? belfor[i] : -1).append("\n");
print(sb);
}
static class Edge {
int from;
int to;
long dis;
public Edge(int from, int to, long dis) { this.from = from; this.to = to; this.dis = dis; }
}
static int toi(String s) { return Integer.parseInt(s); }
static String[] getLine(BufferedReader br) throws IOException { return br.readLine().split(" "); }
static <T> void print(T s) { System.out.print(s); }
static <T> void println(T s) { System.out.println(s); }
}