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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| import java.util.*; class Main{ static int inf = 1000000000; static int[] e; static int[] w; static int[] ne; static int[] h; static int idx = 0; static int[] dist; static boolean[] st; static LinkedList<Integer> queue = new LinkedList<>(); static int[] count; public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); e = new int[m+1]; w = new int[m+1]; ne = new int[m+1]; h = new int[m+1]; dist = new int[n+1]; st = new boolean[n+1]; count = new int[n+1]; Arrays.fill(h, -1); for(int i = 0; i < m; i++){ int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); e[idx] = b; w[idx] = c; ne[idx] = h[a]; h[a] = idx++; } boolean result = spfa(n); System.out.print(result); } public static boolean spfa(int n){ Arrays.fill(dist, inf); queue.offer(1); dist[1] = 0; st[1] = true; while(!queue.isEmpty()){ int t = queue.poll(); st[t] = false; for(int i = h[t]; i != -1; i = ne[i]){ int j = e[i]; if(dist[j] > dist[t] + w[i]){ dist[j] = dist[t] + w[i]; count[j] = count[t] + 1; if(count[j] >= n){ return true; } if(!st[j]){ queue.offer(j); st[j] = true; } } } } return false; } }
|