|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.StringTokenizer; |
| 5 | + |
| 6 | +public class BJ_1956_운동 { |
| 7 | + |
| 8 | + private static final int INF = 987654321; |
| 9 | + |
| 10 | + private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 11 | + private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 12 | + private static StringTokenizer st; |
| 13 | + |
| 14 | + private static int V, E, ans; |
| 15 | + private static int[][] matrix; |
| 16 | + |
| 17 | + public static void main(String[] args) throws IOException { |
| 18 | + init(); |
| 19 | + sol(); |
| 20 | + } |
| 21 | + |
| 22 | + private static void init() throws IOException { |
| 23 | + st = new StringTokenizer(br.readLine()); |
| 24 | + V = Integer.parseInt(st.nextToken()); |
| 25 | + E = Integer.parseInt(st.nextToken()); |
| 26 | + ans = INF; |
| 27 | + |
| 28 | + matrix = new int[V + 1][V + 1]; |
| 29 | + for (int i = 1; i <= V; i++) { |
| 30 | + Arrays.fill(matrix[i], INF); |
| 31 | + } |
| 32 | + |
| 33 | + for (int i = 0; i < E; i++) { |
| 34 | + st = new StringTokenizer(br.readLine()); |
| 35 | + |
| 36 | + int a = Integer.parseInt(st.nextToken()); |
| 37 | + int b = Integer.parseInt(st.nextToken()); |
| 38 | + int w = Integer.parseInt(st.nextToken()); |
| 39 | + |
| 40 | + matrix[a][b] = w; |
| 41 | + } |
| 42 | + |
| 43 | + } |
| 44 | + |
| 45 | + private static void sol() throws IOException { |
| 46 | + for (int k = 1; k <= V; k++) { |
| 47 | + for (int i = 1; i <= V; i++) { |
| 48 | + for (int j = 1; j <= V; j++) { |
| 49 | + matrix[i][j] = Math.min(matrix[i][j], matrix[i][k] + matrix[k][j]); |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + for (int i = 1; i <= V; i++) { |
| 55 | + ans = Math.min(ans, matrix[i][i]); |
| 56 | + } |
| 57 | + |
| 58 | + bw.write(ans != INF ? ans + "" : "-1"); |
| 59 | + |
| 60 | + bw.flush(); |
| 61 | + bw.close(); |
| 62 | + br.close(); |
| 63 | + } |
| 64 | + |
| 65 | +} |
| 66 | +``` |
0 commit comments