// 赋初值 for each vertex v in V dist[v] = INF dist[orig] = 0
Q.offer(orig) while Q is not empty u= Q.poll() for each edge(a, b) in E(G) if dist[a] + w(a, b) < dist[b] // 松弛操作 dist[b] = dist[a] + w(a, b) if b is not in Q Q.offer(b)
classMain { staticfinalintN=2010; staticfinalintM=10010; staticfinalintINF=0x3f3f3f3f; staticint[] h = newint[N]; staticint[] e = newint[M]; staticint[] ne = newint[M]; staticint[] w = newint[M]; staticint idx; staticint[] dist = newint[N]; staticboolean[] st = newboolean[N]; staticint[] cnt = newint[N]; staticint n, m; staticBufferedReadercin=newBufferedReader(newInputStreamReader(System.in));
staticvoidadd(int a, int b, int c) { e[idx] = b; ne[idx] = h[a]; w[idx] = c; h[a] = idx++; }
publicstaticvoidmain(String[] args)throws Exception { String[] str = cin.readLine().split(" "); n = Integer.parseInt(str[0]); m = Integer.parseInt(str[1]); int a, b, c; Arrays.fill(h, -1); for (inti=0; i < m; ++i) { str = cin.readLine().split(" "); a = Integer.parseInt(str[0]); b = Integer.parseInt(str[1]); c = Integer.parseInt(str[2]); add(a, b, c); } booleanres= spfa(); if (res) System.out.println("Yes"); else System.out.println("No"); cin.close(); }
staticbooleanspfa() { Arrays.fill(dist, INF); dist[1] = 0; Queue<Integer> q = newLinkedList<>(); // for (inti=1; i <= n; ++i) { st[i] = true; q.offer(i); } while (!q.isEmpty()) { intcur= q.poll();
st[cur] = false; // st数组,true:代表队列中有该顶点 for (inti= h[cur]; i != -1; i = ne[i]) { intj= e[i]; if (dist[j] > dist[cur] + w[i]) { dist[j] = dist[cur] + w[i]; cnt[j] = cnt[cur] + 1; if (cnt[j] >= n) returntrue; if (!st[j]) { q.offer(j); st[j] = true; } } } } returnfalse; } }