It is the Bellman-ford algorithm for queue optimization.
The optimization principle is: The next relaxation operation is updated the point of the dis is actually related to the last updated point! If the last updated point has an edge pointing to a point V, then the next time, Point V is the point at which the dis may be updated.
As with the Bellman-ford algorithm, it can be used to find the shortest path with negative weights, and if there is a loop with a negative weight that can be reached from the source point, False indicates no solution, since the total cost can continue to circulate in this loop, and returns True if it does not exist.
#include <iostream>#include<algorithm>#include<cstring>#include<string>#include<Set>#include<queue>using namespacestd;#defineINF 0x3f3f3f3f#defineM (A, B) memset (A, B, sizeof (a))Const intMAXN = ++5;structEdge {int from, to, Dist;};structSPFA {intD[MAXN], CNT[MAXN], P[MAXN]; intN, M; BOOLINQ[MAXN]; Vector<int>G[MAXN]; Vector<Edge>edges; voidInitintN) { This->n =N; for(inti =1; I <= N; ++i) g[i].clear (); Edges.clear (); } voidAddedge (int from,intTo,intDist) {Edges.push_back (edge{ from, to, dist}); intm =edges.size (); g[ from].push_back (M-1); } BOOLSPFA (ints) {M (d, INF); M (CNT,0); M (INQ,0); D[s]=0; Queue<int>Q; Q.push (s); Inq[s]=true; while(!Q.empty ()) { intU =Q.front (); Q.pop (); Inq[u]=false; for(inti =0; I < g[u].size (); ++i) {Edge&e =Edges[g[u][i]]; if(D[e.to] > D[u] +e.dist) {d[e.to]= D[u] +e.dist; P[e.to]=G[u][i]; if(!Inq[e.to]) {Q.push (e.to); Inq[e.to]=true; if(++cnt[e.to] > N)return false; } } } } return true; }}; SPFA Solver;intMain () {intN, M, A, B, C; while(Cin >> M >>N) {solver.init (n); while(m--) {cin>> a >> b >>C; Solver. Addedge (A, B, c); Solver. Addedge (b, A, c); } SOLVER.SPFA (1); cout<< Solver.d[n] <<Endl; } return 0;}
SPFA algorithm template to find the shortest circuit with negative weight edge