Poj 3259 (Bellman_Ford determines the negative ring)

Source: Internet
Author: User

John's farm contains n plots of land, m links are connected to two plots of land, k are wormhole holes, and the wormhole holes are one-way routes that not only send you to your destination, and the time will go backwards. Our task is to know if we will return again after starting from a certain place and see ourselves before leaving. Idea: the edge connected by the wormhole is a negative weight. If there is a negative ring on the way, he can keep following this change, and the time must be a negative value.

# Include <string. h> # include <stdio. h> const int N = 510; const int inf = 0x3fffffff; int start, num, n, dist [N]; struct edge {int st, ed, w ;} e [6000]; void addedge (int x, int y, int w) {e [num]. st = x; e [num]. ed = y; e [num ++]. w = w;} int Bellman_Ford () {int flag = 0, I, u, v, j; for (I = 1; I <= n; I ++) dist [I] = inf; dist [start] = 0; for (I = 1; I <n; I ++) // n-1 relaxation {for (j = 0; j <num; j ++) {u = e [j]. st; v = e [j]. ed; if (dist [v]> dist [u] + e [j]. w) {dist [v] = dist [u] + e [j]. w; flag = 1 ;}}if (flag = 0) break;} for (I = 0; I <num; I ++) if (dist [e [I]. ed]> dist [e [I]. st] + e [I]. w) // return 1; return 0;} int main () {int m, I, x, y, k, t, Case; scanf ("% d", & Case); while (Case --) {scanf ("% d", & n, & m, & k ); num = 0; for (I = 1; I <= m; I ++) {scanf ("% d", & x, & y, & t); addedge (x, y, t); addedge (y, x, t) ;}for (I = 0; I <k; I ++) {scanf ("% d", & x, & y, & t); addedge (x, y,-t);} start = 0; if (Bellman_Ford () 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.