Poj 3259 wormholes (Bellman-Ford)

Source: Internet
Author: User

Link: poj 3259

A famer has some farms, some of which contain some fields, some wormhole holes in the field, and a path (two-way) between the field and the field ), that is, the time from A to B and from B to a is C. the nature of wormhole: Time backflow. That is, the time spent from A to B through the wormhole is-C (one-way). I asked if he could go back to the starting point through the nature of the wormhole.

Idea: This question is actually to determine whether there is a negative weight loop. You can use the spfa algorithm or the Bellman-Ford algorithm to determine whether there is a negative weight loop. If a negative weight loop exists, this can be achieved; otherwise, it cannot.

Bellman-Ford Algorithm

# Include <stdio. h> # include <limits. h> struct Stu {int A, B, C;} edge [6000]; int dis [550], n, m; int bellmanford () {int flag = 0, I, j; for (I = 1; I <= N; I ++) dis [I] = int_max; DIS [1] = 0; for (I = 1; I <= n-1; I ++) for (j = 1; j <= m; j ++) if (DIS [edge [J]. a]! = Int_max & dis [edge [J]. a] + edge [J]. c <dis [edge [J]. b]) dis [edge [J]. b] = dis [edge [J]. a] + edge [J]. c; for (I = 1; I <= m; I ++) // determine the negative weight loop if (DIS [edge [I]. a]! = Int_max & dis [edge [I]. a] + edge [I]. c <dis [edge [I]. b]) {flag = 1; break;} return flag;} int main () {int T, I, J, K, flag; scanf ("% d ", & T); While (t --) {scanf ("% d", & N, & M, & K); j = 1; for (I = 1; I <= m; I ++) {scanf ("% d", & edge [J]. a, & edge [J]. b, & edge [J]. c); j ++; edge [J]. A = edge [J-1]. b; // The path is a bidirectional edge [J]. B = edge [J-1]. a; edge [J]. C = edge [J-1]. c; j ++ ;}for (I = 1; I <= K; I ++) {scanf ("% d", & edge [J]. a, & edge [J]. b, & edge [J]. c); edge [J]. C =-edge [J]. c; // the wormhole is unidirectional and the time is negative J ++;} M = J-1; flag = bellmanford (); If (FLAG) printf ("Yes \ n "); else printf ("NO \ 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.