|
| 1 | +import java.io.*; |
| 2 | +import java.util.*; |
| 3 | + |
| 4 | +public class Main { |
| 5 | + private static final int INF = (int)1e9; |
| 6 | + |
| 7 | + public static void main(String[] args) throws IOException{ |
| 8 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 9 | + |
| 10 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 11 | + |
| 12 | + int n = Integer.parseInt(st.nextToken()); |
| 13 | + int m = Integer.parseInt(st.nextToken()); |
| 14 | + |
| 15 | + int[][] graph = new int[n+1][n+1]; |
| 16 | + |
| 17 | + for(int i=0; i<=n; i++) { |
| 18 | + Arrays.fill(graph[i], INF); |
| 19 | + graph[i][i] = 0; |
| 20 | + } |
| 21 | + |
| 22 | + for(int i=0; i<m; i++) { |
| 23 | + st = new StringTokenizer(br.readLine()); |
| 24 | + |
| 25 | + int a = Integer.parseInt(st.nextToken()); |
| 26 | + int b = Integer.parseInt(st.nextToken()); |
| 27 | + int c = Integer.parseInt(st.nextToken()); |
| 28 | + |
| 29 | + graph[a][b] = c; |
| 30 | + } |
| 31 | + |
| 32 | + for(int k=1; k<=n; k++) { |
| 33 | + for(int i=1; i<=n; i++) { |
| 34 | + for(int j=1; j<=n; j++) { |
| 35 | + graph[i][j] = Math.min(graph[i][j], graph[i][k]+graph[k][j]); |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + int min = Integer.MAX_VALUE; |
| 41 | + for(int i=1; i<=n; i++) { |
| 42 | + for(int j=i+1; j<=n; j++) { |
| 43 | + if(graph[i][j] == INF || graph[j][i] == INF) continue; |
| 44 | + min = Math.min(min, graph[i][j] + graph[j][i]); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + if(min == Integer.MAX_VALUE) min = -1; |
| 49 | + System.out.println(min); |
| 50 | + } |
| 51 | + |
| 52 | + private static class Edge { |
| 53 | + int to; |
| 54 | + int cost; |
| 55 | + |
| 56 | + public Edge(int to, int cost) { |
| 57 | + this.to = to; |
| 58 | + this.cost = cost; |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments