Bellman_fordAlgorithmCheck whether a negative weight loop exists in the graph. If the negative weight loop does not exist in the figure, the maximum short-circuit path goes through n-1 nodes. If the number exceeds n-1 nodes, the negative weight loop exists.
# Include <cstdio> # include <cstring> # include <queue> # include <vector> using namespace STD; const int INF = 100000000; const int maxn = 1005; vector <int> G [maxn]; int weight [maxn] [maxn]; queue <int> q; bool INQ [maxn]; int d [maxn]; int count; int n, m; bool bellman_ford () {for (INT I = 0; I <n; I ++) d [I] = inf, INQ [I] = false; d [0] = 0; Count = 0; q. push (0); INQ [0] = true; while (! Q. empty () {int u = Q. front (); q. pop (); INQ [u] = false; For (INT I = 0; I <(INT) g [u]. size (); I ++) {int v = G [u] [I]; If (d [v]> d [u] + weight [u] [v]) {d [v] = d [u] + weight [u] [v]; If (! INQ [v]) {INQ [v] = true; count ++; If (count> = N) return true; q. push (v) ;}}}return false;} int main () {int t; scanf ("% d", & T); While (t --) {scanf ("% d", & N, & M); For (INT I = 0; I <n; I ++) g [I]. clear (); For (INT I = 0; I <m; I ++) {int U, V, W; scanf ("% d ", & U, & V, & W); G [u]. push_back (V); weight [u] [v] = W;} If (bellman_ford () puts ("Possible \ n "); else puts ("Not possible \ n");} return 0 ;}