Va 558 bellman_ford

Source: Internet
Author: User

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 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.