SPFA
原创建时间:2017-12-30 21:05:19
简单的SPFA最短路模板,适用于图的边权有负数的情况。
算法实现:
我们用数组d记录每个结点的最短路径估计值,而且用邻接表来存储图G。运用动态逼近法:设立一个先进先出的队列用来保存待优化的结点,优化时每次取出队首结点u,并且用u点当前的最短路径估计值对离开u点所指向的结点v进行松弛操作,如果v点的最短路径估计值有所调整,且v点不在当前的队列中,就将v点放入队尾。这样不断从队列中取出结点来进行操作,直至队列空为止。
代码实现:
给一个指针实现
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <queue> using namespace std; #define MAXN 2500 + 5 #define DEBUG(x) cerr << #x << '=' << x const int Inf = 2e31-1; struct Node; struct Edge; struct Node{ Edge *firstEdge; int dist; bool inQueue; } node[MAXN]; struct Edge{ Node *s,*t; int w; Edge *next; Edge(Node *s,Node *t,int w) : s(s),t(t),w(w),next(s->firstEdge){} }; inline void add(const int &s,const int &t,const int &w){ node[s].firstEdge = new Edge(&node[s],&node[t],w); node[t].firstEdge = new Edge(&node[t],&node[s],w); } inline int spfa(const int &s,const int &t,const int &n){ for (int i = 1;i <= n;i++){ node[i].dist = Inf; node[i].inQueue = false; //将所有节点的在队列的情况设为false } queue<Node *> q; q.push(&node[s]); node[s].dist = 0; node[s].inQueue = true; while (!q.empty()){ Node *u = q.front(); q.pop(); u->inQueue = false; for (Edge *e = u->firstEdge;e;e = e->next){ Node *v = e->t; if (v->dist > u->dist + e->w){ v->dist = u->dist + e->w; if (!v->inQueue){ q.push(v); v->inQueue = true; } } } } return node[t].dist; } int main(int argc, char const *argv[]) { int n,m,s,t; scanf("%d %d %d %d",&n,&m,&s,&t); for (int i = 1;i <= m;i++){ int u,v,w; scanf("%d %d %d",&u,&v,&w); add(u,v,w); } printf("%d",spfa(s,t,n)); return 0; }
相关推荐
boneix 2020-10-21
seanzed 2020-10-15
ifconfig 2020-10-14
学留痕 2020-09-20
往后余生 2020-09-17
kka 2020-09-14
redis 2020-09-07
lzccheng 2020-09-06
soyo 2020-08-31
stonerkuang 2020-08-18
LxyPython 2020-08-17
raksmart0 2020-08-17
Lzs 2020-08-14
MrHaoNan 2020-07-31
80530895 2020-07-05
lengyu0 2020-06-28
YarnSup 2020-06-28
huanglianhuabj00 2020-06-27