SPFA(G,w,s)
1. INITIALIZE-SINGLE-SOURCE(G,s)
2. INITIALIZE-QUEUE(Q)
3. ENQUEUE(Q,s)
4. While Not EMPTY(Q)
5. Do u<-DLQUEUE(Q)
6. For 每条边(u,v) in E[G]
7. Do tmp<-d[v]
8. Relax(u,v,w)
9. If (d[v] < tmp) and (v不在Q中)
10. ENQUEUE(Q,v)
#include<iostream> using namespace std; #define MAX 500 #define maxn 0x7fffffff int q[3*MAX+1],d[3*MAX+1]; bool flag[3*MAX+1]; int n,from,to; int spfa()//源点from 目标点to { memset(flag,0,sizeof(flag)); int i,j,rear,front,now; rear=front=0; q[rear++]=from; flag[from]=1; for(i=1;i<=n;i++) d[i]=maxn; d[from]=0; while(front<=rear) { now=q[front++]; flag[now]=0; for(i=1;i<=n;i++) { if(f[now][i]&&d[now]+f[now][i]<d[i]) { d[i]=d[now]+f[now][i]; if(!flag[i]) { flag[i]=1; q[rear++]=i; } } } } return d[to]; }
|