Bellman-Ford algorithm (Bellman - Ford algorithm)

definition

Bellman - Ford algorithm, an algorithm for solving single-source shortest path problem, by Richard Berman (Richard Bellman) and Lester Ford founded.

It is the principle of operation of FIG relaxation, to give all possible shortest paths. Its better than Dijkstra's algorithm is edge weights can be negative, simple, the disadvantage is the time complexity is too high.

principle

Bellman-Ford algorithm by relaxation (if dist [v] <dist [u] + w, the dist [v] = dist [u] + w), repeated use of existing edges to update the shortest distance.

If the absence of negative cycles, will be terminated after (n-1) relaxation times. Because the shortest path between any two points after most (n-2) dots, so after the (n-1) times the shortest path can be obtained after the operation.

If the negative cycles exist, then the n-th relaxation operation will still succeed, Bellman-Ford algorithm is to use the negative nature of the judgment ring.

achieve

#include<bits/stdc++.h>
using namespace std;
const int inf=0x3f3f3f3f;
const int maxn=10005;
struct node
{
  int u,v,w;
}edge[maxn];
int dis[maxn],n,m;
int Bellman_Ford(int s);
int main()
{
  int i;   
  scanf("%d%d",&n,&m);
  for(i=1;i<=m;i++)  scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].w);
  if(Bellman_Ford(1)) printf("有负环\n");
  system("pause");
  return 0;
}
int Bellman_Ford(int s)
{
  int check,flag=0,i,j;
  fill(dis,dis+maxn,inf);  dis[s]=0;
  for(j=1;j<=n-1;j++)
  {
    check=0;
    for(i=1;i<=m;i++)
      if(dis[edge[i].v]>dis[edge[i].u]+edge[i].w)
      {
        dis[edge[i].v]=dis[edge[i].u]+edge[i].w;
        check=1;
      }
    if(!check)break;
  }

  for(i=1;i<=m;i++)
    if(dis[edge[i].v]>dis[edge[i].u]+edge[i].w)
      {
        flag=1;
        break;
      }

  if(flag) return 1;
  else
    for(i=1;i<=n;i++)
      printf("%d->%d   %d\n",s,i,dis[i]);
  return 0;
}

Guess you like

Origin www.cnblogs.com/VividBinGo/p/11615725.html