Bellman-Ford&SPFA算法

<Bellman-Ford算法> 

 Dijkstra算法中要求边的权非负,如果遇到负权,则可以采用Bellman-Ford算法。

  适用条件&范围

  1.单源最短路径(从源点s到其它所有顶点v);

  2.有向图&无向图(无向图可以看作(u,v),(v,u)同属于边集E的有向图);

  3.边权可正可负(如有负权回路输出错误提示);

  4.差分约束系统;

  算法描述

  1.对每条边进行|V|-1次Relax操作; ---------- |V| 表示节点的个数

  2.如果存在(u,v)∈E使得dis[u]+w<dis[v],则存在负权回路;否则dis[v]即为s到v的最短距离,pre [v]为前驱。-----------dis[u] 表示经过第 1 步后s到u的最短距离,w表示某边权值,pre[v]所表示的就是上一次更新dis[v]的中间点即第 1 步中的u点

  伪代码

  -------------------PASCAL------------

  For i:=1 to |V|-1 do

  For 每条边(u,v)∈E do

  Relax(u,v,w);

  For每条边(u,v)∈E do

  If dis[u]+w<dis[v] Then Exit(False)

  -----------------C&C++--------------

  void bellman_ford(int v)

  {

  for 1 to n

  initialize dist[v]; //此时只经过一条边
  for 2 to n-1 (i) //经过的边数不大于i条时
  for 1 to n (j) //对于每一个目标顶点
  for 1 to n (k) //经过该顶点时,与当前最小值比较,并更新当前值
  if edge[k][j] > 0 && dist[k] > edge[k][j]+dist[j]
  更新当前值
  }
  时空复杂度
  算法时间复杂度O(VE)。因为算法简单,适用范围又广,虽然复杂度稍高,仍不失为一个很实用的算法。
  参考代码
  ----------------PASCAL-----------------
  {单源最短路径的Bellman-ford算法
  执行v-1次,每次对每条边进行松弛操作
  如有负权回路则输出"Error"
  }
  const
  maxn=100;
  maxe=maxn*(maxn-1)div 2;
  type
  edge=record
  a,b,w :integer;
  end;
  var
  edges :array[1..maxe]of edge;
  dis :array[1..maxn]of integer;
  pre :array[1..maxn]of integer;
  e,n,s :integer;
  procedure init;
  var
  i :integer;
  begin
  e:=0;
  assign(input,'g.in');reset(input);
  readln(n,s);
  while not eof do
  begin
  inc(e);
  with edges[e] do readln(a,b,w);
  end;
  fillchar(dis,sizeof(dis),$7f);//$7f是什么,解释替换 $7f 是127 $在pascal中代表后面的数是16进制
  dis[s]:=0;pre[s]:=s;
  end;
  procedure relax(u,v,w:integer);
  begin
  if dis[u]+w<dis[v] then
  begin
  dis[v]:=dis[u]+w;
  pre[v]:=u;
  end
  end;
  function bellman_ford:boolean;
  var
  i,j :integer;
  begin
  for i:=1 to n-1 do
  for j:=1 to e do
  with edges[j] do relax(a,b,w);
  for i:=1 to e do
  with edges[i] do
  if dis[a]+w<dis[b] then exit(false);
  exit(true)
  end;
  procedure print_path(i:integer);
  begin
  if pre[i]<>s then print_path(pre[i]);
  write('-->',i)
  end;
  procedure show;
  var
  i :integer;
  begin
  for i:=1 to n do
  begin
  write(i:3,':',dis[i]:3,':',s);
  print_path(i);
  writeln
  end;
  end;
  {========main========}
  begin
  init;
  if bellman_ford then show
  else writeln('Error!!')
  end.
  
  --------------------Matlab-------------
  function ford(d,n,s) % d为已知图的邻接矩阵,n为顶点数(各顶点标号为1,2...,n),s为源点标号
  for i=1:n %初始化dist,pre
  dist(i)=inf; %dist(i)为s,i之间的最短路的长度
  pre(i)=NaN; %pre(i)为s到i的最短路上i的前一个顶点
  end
  dist(s)=0;
  for k=1:n-1
  for i=1:n %松弛操作
  for j=1:n
  if d(i,j)~=inf
  if dist(j)>dist(i)+d(i,j)
  dist(j)=dist(i)+d(i,j);
  pre(j)=i;
  end
  end
  end
  end
  end
  for i=1:n
  for j=1:n
  if d(i,j)~=inf
  if dist(i)+d(i,j)<dist(j)%判断有无负权回路
  error('negetive weight circut');
  end
  end
  end
  end
  dist
  pre
  end
  

引申:SPFA算法

  算法简介

  SPFA(Shortest Path Faster Algorithm)是Bellman-Ford算法的一种队列实现,减少了不必要的冗余计算。

算法流程

  算法大致流程是用一个队列来进行维护。 初始时将源加入队列。 每次从队列中取出一个元素,并对所有与他相邻的点进行松弛,若某个相邻的点松弛成功,则将其入队。 直到队列为空时算法结束。

  算法代码

  Procedure SPFA;

  Begin

  initialize-single-source(G,s);

  initialize-queue(Q);

  enqueue(Q,s);

  while not empty(Q) do begin

  u:=dequeue(Q);

  for each v∈adj[u] do begin

  tmp:=d[v];

  relax(u,v);

  if (tmp<>d[v]) and (not v in Q) then enqueue(v);

  end;

  end;

  End;
POJ3259

Wormholes
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 7131   Accepted: 2499

Description

While exploring his many farms, Farmer John has discovered a number of amazing wormholes. A wormhole is very peculiar because it is a one-way path that delivers you to its destination at a time that is BEFORE you entered the wormhole! Each of FJ's farms comprises N (1 ≤ N ≤ 500) fields conveniently numbered 1..N, M (1 ≤ M ≤ 2500) paths, and W (1 ≤ W ≤ 200) wormholes.

As FJ is an avid time-traveling fan, he wants to do the following: start at some field, travel through some paths and wormholes, and return to the starting field a time before his initial departure. Perhaps he will be able to meet himself :) .

To help FJ find out whether this is possible or not, he will supply you with complete maps to F (1 ≤ F ≤ 5) of his farms. No paths will take longer than 10,000 seconds to travel and no wormhole can bring FJ back in time by more than 10,000 seconds.

Input

Line 1: A single integer, F. F farm descriptions follow.
Line 1 of each farm: Three space-separated integers respectively: N, M, and W
Lines 2.. M+1 of each farm: Three space-separated numbers ( S, E, T) that describe, respectively: a bidirectional path between S and E that requires T seconds to traverse. Two fields might be connected by more than one path.
Lines M+2.. M+ W+1 of each farm: Three space-separated numbers ( S, E, T) that describe, respectively: A one way path from S to E that also moves the traveler back T seconds.

Output

Lines 1.. F: For each farm, output "YES" if FJ can achieve his goal, otherwise output "NO" (do not include the quotes).

Sample Input

2
3 3 1
1 2 2
1 3 4
2 3 1
3 1 3
3 2 1
1 2 3
2 3 4
3 1 8

Sample Output

NO
YES

Hint

For farm 1, FJ cannot travel back in time.
For farm 2, FJ could travel back in time by the cycle 1->2->3->1, arriving back at his starting location 1 second before he leaves. He could start from anywhere on the cycle to accomplish this.

Source

USACO 2006 December Gold
#include<stdio.h> int n,d[1005]; struct node { int a,b,c; }edge[10005]; bool bellman(int m) { int i,j,f; for(i=2;i<=n;i++) d[i]=999999; d[1]=0; for(i=1;i<n;i++) { for(f=j=1;j<=m;j++) if(d[edge[j].a]>d[edge[j].b]+edge[j].c) d[edge[j].a]=d[edge[j].b]+edge[j].c+(f=0); if(f) break; } for(j=1;j<=m;j++) if(d[edge[j].a]>d[edge[j].b]+edge[j].c) return 0; return 1; } int main() { int t,m,w,a,b,c,k; scanf("%d",&t); while(t--) { scanf("%d%d%d",&n,&m,&w); k=0; while(m--) { scanf("%d%d%d",&a,&b,&c); edge[++k].a=a; edge[k].b=b; edge[k].c=c; edge[++k].a=b; edge[k].b=a; edge[k].c=c; } while(w--) { scanf("%d%d%d",&a,&b,&c); edge[++k].a=b; edge[k].b=a; edge[k].c=-c; } if(bellman(k)) puts("NO"); else puts("YES"); } }

你可能感兴趣的:(Bellman-Ford&SPFA算法)