On the shortest path problem, we have recently learned four methods--bellman algorithm, Adjacency table method, Dijkstra algorithm and Floyd-warshall algorithm.
The simplest of these is the Bellman algorithm, which stores the start, end, and path lengths of an edge by defining an edge structure, and then accesses each edge continuously through a while (1) dead loop, updating the source point to the shortest distance from each point until the end of the update. At this point, the shortest distance from the source to the other points is obtained. Enclose the Code section:
#include <iostream>
#define INF 100000000
using namespace Std;
struct EG
{
int s,t;
int C;
};//the structure of the edge, storing the element as the starting point S, the end point T, the length of the path s to t
eg eg[100];
int dis[100];
void Bellman (int s,int E)
{
Fill (dis,dis+100,inf);//Initialize all shortest distances to INF;
dis[s]=0;//but the shortest distance from the source point is 0, oneself to oneself
while (1)
{
BOOL update= false;
for (int i=0;i<e;i++)
{
eg E=eg[i];
if (Dis[e.s]!=inf && dis[e.t]>dis[e.s]+e.c)//update
{
dis[e.t]=dis[e.s]+e.c;
Update = TRUE;
}
}
if (!update)//If all edges of the traversal are no longer updated, jump out of the loop
Break
}
}
int main ()
{
int e;//The variable that defines the edge
Cin >> E;
for (int i=0;i<e;i++)//Direct Storage Edge
{
CIN >> eg[i].s >> eg[i].t >> eg[i].c;
}
int S1;
CIN >> s1;//Defining a source point
Bellman (s1,e);
int t;
CIN >> T;
cout << dis[t] << Endl;
return 0;
}
In the code we can analyze, the time complexity of the bellman algorithm is O (v*e), while loop is executed at most V-1 times; the bellman algorithm still has a problem in the negative circle, If there is a negative circle in the graph where the source point S can be reached (the ring exists in the figure and there is a negative edge in the ring (the value of the Edge is negative)), when the while loop is updated, go to this negative circle, dis "e.t" >dis[e.s]+ E.C is a constant set up, each time the while loop will be updated, so that the method of just the word will form a dead loop, so, with the bellman algorithm to ensure that there is no source point s can reach the negative circle. Enclose the code to find the negative circle:
BOOL Find_negative_loop ()
{
memset (dis,0,sizeof (DIS));//note differs from Fill's notation (Fill (dis,dis+e,inf))
for (int i=1;i<=v;i++)
for (int j=0;j<e;j++)
{
eg E=eg[j];
if (dis[e.t]>dis[e.s]+e.c)
{
dis[e.t]=dis[e.s]+e.c;
if (i==v) return true;
}
}
}
--bellman algorithm for shortest path problem