|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +class Edge { |
| 6 | + int from, to, cost; |
| 7 | + |
| 8 | + public Edge(int from, int to, int cost) { |
| 9 | + this.from = from; |
| 10 | + this.to = to; |
| 11 | + this.cost = cost; |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +public class Main { |
| 16 | + static final long INF = 987654321; |
| 17 | + static int n, m; |
| 18 | + static List<Edge> edges = new ArrayList<>(); |
| 19 | + static long[] dist; |
| 20 | + |
| 21 | + public static void main(String[] args) throws IOException { |
| 22 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 23 | + StringTokenizer st; |
| 24 | + |
| 25 | + st = new StringTokenizer(br.readLine()); |
| 26 | + n = Integer.parseInt(st.nextToken()); |
| 27 | + m = Integer.parseInt(st.nextToken()); |
| 28 | + |
| 29 | + dist = new long[n + 1]; |
| 30 | + |
| 31 | + for (int i = 0; i < m; i++) { |
| 32 | + st = new StringTokenizer(br.readLine()); |
| 33 | + int from = Integer.parseInt(st.nextToken()); |
| 34 | + int to = Integer.parseInt(st.nextToken()); |
| 35 | + int cost = Integer.parseInt(st.nextToken()); |
| 36 | + edges.add(new Edge(from, to, cost)); |
| 37 | + } |
| 38 | + |
| 39 | + if (!bellmanFord(1)) { |
| 40 | + System.out.println(-1); |
| 41 | + } else { |
| 42 | + for (int i = 2; i <= n; i++) { |
| 43 | + if (dist[i] == INF) |
| 44 | + System.out.println(-1); |
| 45 | + else |
| 46 | + System.out.println(dist[i]); |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + static boolean bellmanFord(int start) { |
| 52 | + Arrays.fill(dist, INF); |
| 53 | + dist[start] = 0; |
| 54 | + |
| 55 | + for (int i = 1; i < n; i++) { |
| 56 | + for (Edge e : edges) { |
| 57 | + if (dist[e.from] != INF && dist[e.to] > dist[e.from] + e.cost) { |
| 58 | + dist[e.to] = dist[e.from] + e.cost; |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + for (Edge e : edges) { |
| 64 | + if (dist[e.from] != INF && dist[e.to] > dist[e.from] + e.cost) { |
| 65 | + return false; |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + return true; |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +``` |
0 commit comments