Shortest path algorithm (Bellman-ford algorithm)

Source: Internet
Author: User
Tags acos cmath

The Bell-Ford algorithm is similar to the Dicos algorithm , which is based on the relaxation operation, that is, the estimated shortest path value is gradually replaced by a more accurate value, until the optimal solution is obtained. In two algorithms, the estimated distance between each edge of the calculation is greater than the true value, and is replaced by the minimum length of the newly found path. However, the DICOS algorithm chooses the non-processed node with the least weight by greedy method, and then relaxes the edge of it, while the Bertelsmann-Ford algorithm simply relaxes all the edges, altogether | V | − 1 times, where | V | Is the number of points in the graph. In a repeating calculation, the number of edges that have been calculated to get the correct distance is increasing until all edges have been computed with the correct path. Such a strategy makes the Bidicos-Ford algorithm suitable for more types of input.

Most of the Bertelsmann-Ford algorithms Run O (| V| | E|) Times, | V| and | E| is the number of nodes and edges, respectively).

The most important differencebetween the Dicos -Ford algorithm and the algorithm is that the Bellman-ford algorithm can exist negative weights, while the Dijkstra algorithm does not allow negative weight edges;

Steps for the Bellman-ford algorithm:

Step 1: Initialize the diagram

Step 2: Relax each edge

Step 3: Check the negative weight ring

procedure Bellmanford (list vertices, list edges, vertex source)//the implementation reads into the list of edges and nodes and writes the shortest path information to two arrays (distance and predecessor)//Step 1: Initialize the diagram    forEach vertex vinchvertices:ifV isSource then Distance[v]: =0       ElseDISTANCE[V]: =Infinity Predecessor[v]:=NULL   //Step 2: Repeat the slack for each edge    forI from 1To size (vertices)-1:        forEach edge (U, v) with weight Winchedges:ifDistance[u] + W <Distance[v]: distance[v]:= Distance[u] +W Predecessor[v]:=u//Step 3: Check the negative weight ring    forEach edge (U, v) with weight Winchedges:ifDistance[u] + W <Distance[v]: Error"The graph contains a negative weight ring"
View Code

POJ 3259

Test instructions: John has path and wormhole between N farms, path+ time, wormhole-time, and asks if there is a certain satisfaction, John travels some paths and wormholes, back to the Origin time is negative.

Idea: Standard bellman-ford algorithm; (check negative weight ring)

#include <iostream>#include<algorithm>#include<cstdlib>#include<ctime>#include<cmath>#include<cstdio>#include<string>#include<cstring>#include<vector>#include<queue>#include<stack>#include<Set>#defineC_false Ios_base::sync_with_stdio (FALSE); Cin.tie (0)#defineINF 0x3f3f3f3f#defineINFL 0x3f3f3f3f3f3f3f3f#defineZero_ memset (x, y, sizeof (x))#defineZero (x) memset (x, 0, sizeof (x))#defineMAX (x) memset (x, 0x3f, sizeof (x))#defineSWA (x, y) {LL s;s=x;x=y;y=s;}using namespacestd;#defineN 505#defineLowbit (k) k& (-K)Const DoublePI = ACOs (-1.0);Const intM = 1e5+7; typedefLong LongLL;intFarm, field, path, wormhole, sum;intDis[n];structway{intBegin, End, Time;} A[n*N];BOOLBellmanford () { for(inti =2; I <= field; i++) dis[i] = M;///initialization operation;     for(inti =1; i < field; i++) {///relaxation operation;         for(intj =1; J <= Sum; J + +){            if(Dis[a[j]. END] > Dis[a[j]. Begin] +A[j]. Time) Dis[a[j]. END]= Dis[a[j]. Begin] +A[j].        time; }    }     for(inti =1; I <= sum; i++)///check the negative weight ring;        if(Dis[a[i]. END] >dis[a[i]. Begin] +A[i]. Time)return false; return true;}intMain () {//freopen ("In.txt", "R", stdin); //freopen ("OUT.txt", "w", stdout); //Ios_base::sync_with_stdio (false); Cin.tie (0);scanf"%d", &Farm);  while(farm--){        intS, E, t, k =0; scanf ("%d%d%d", &field, &path, &wormhole);  for(inti =0; I < path; i++) {scanf ("%d%d%d", &s, &e, &t); K++; A[K]. Begin=s; A[K]. End=e; A[K]. time=BT; K++; A[K]. Begin=e; A[K]. End=s; A[K]. time=T; }         for(inti =0; I < wormhole; i++) {scanf ("%d%d%d", &s, &e, &t); K++; A[K]. Begin=s; A[K]. End=e; A[K]. time= -T; } Sum=K; if(! Bellmanford ()) printf ("yes\n"); Elseprintf"no\n"); }    return 0;}
View Code

POj 1860

Test instructions: N currencies, M trading points, each transaction to receive Commission, to find out whether there is a value-added method.

Idea: Just opposite to the Bellman-ford algorithm, check the positive weight ring;

The Benquan of A to B is: b = (a-cab) *rab;

In the discuss, there was a discussion about whether the ring contained the S point, in fact the ring does not necessarily contain S point,

Because as long as you find a ring that can increase wealth infinitely, add wealth and then return to the S point.

So the ring is not necessary to contain the S point.

#include <iostream>#include<algorithm>#include<cstdlib>#include<ctime>#include<cmath>#include<cstdio>#include<string>#include<cstring>#include<vector>#include<queue>#include<stack>#include<Set>#defineC_false Ios_base::sync_with_stdio (FALSE); Cin.tie (0)#defineINF 0x3f3f3f3f#defineINFL 0x3f3f3f3f3f3f3f3f#defineZero_ memset (x, y, sizeof (x))#defineZero (x) memset (x, 0, sizeof (x))#defineMAX (x) memset (x, 0x3f, sizeof (x))#defineSWA (x, y) {LL s;s=x;x=y;y=s;}using namespacestd;#defineN 505#defineLowbit (k) k& (-K)Const DoublePI = ACOs (-1.0);Const intM = 1e5+7; typedefLong LongLL;intN, M, S, sum;DoubleRab, Cab, Rba, Cba, V;DoubleDis[n];structway{intBegin, End; DoubleChange , rate;} A[n*N];BOOLBellmanford () {zero (dis); Dis[s]=V; intSign ;  for(inti =0; I <= N; i++) { sign=0;  for(intj =1; J <= Sum; J + +){            if(Dis[a[j]. END] < (Dis[a[j]. Begin]-a[j]. Change) *A[j]. Rate) Dis[a[j]. END]= (Dis[a[j]. Begin]-a[j]. Change) *A[j].               rate; Sign=1; }        if(!Sign ) Break; }     for(intj =1; J <= Sum; J + +){            if(Dis[a[j]. END] < (Dis[a[j]. Begin]-a[j]. Change) *A[j]. Rate)return true; }    return false;}intMain () {//freopen ("In.txt", "R", stdin); //freopen ("OUT.txt", "w", stdout); //Ios_base::sync_with_stdio (false); Cin.tie (0);     while(~SCANF ("%D%D%D%LF", &n, &m, &s, &V)) {        intX, y, k =0;  for(inti =0; I < m; i++) {scanf ("%D%D%LF%LF%LF%LF", &x, &y, &rab, &Cab,&Rba,&Cba); ++K; A[K]. Begin=x; A[K]. End=y; A[K]. Change=Cab; A[K]. Rate=Rab; ++K; A[K]. Begin=y; A[K]. End=x; A[K]. Change=Cba; A[K]. Rate=Rba; } Sum=K; if(Bellmanford ()) printf ("yes\n"); Elseprintf"no\n"); }    return 0;}
View Code

Shortest path algorithm (Bellman-ford algorithm)

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.