# Single Source Shortest Path algorithm

Source: Internet
Author: User

Directory

• Basic properties
• Bellman Ford algorithm
• SPFA (shortest Path Faster algorithm) algorithm
• Dijkstra algorithm
• Example Exercises

Introduction to Main reference algorithms

Basic properties
``使用min_w(s,v)表示源节点s到v的最短路径长度；w(u,v)表示节点u到v的权重；u.d表示源节点s到节点u的当前路径长度；``
Slack operation
``relax(u,v,w){    if(u.d + w < v.d)    {           v.d = u.d + w;    }   ``
Triangular inequalities
``    min_w(s,v) <= min_w(s,u) + w(u,v);``
Path Relaxation Properties
``    如果p(v0, v1, v2, ...... , vk)为v0到vk 的最短路径，并且对边的松弛次序为(v0,v1),(v1,v2),(v2,v3),......(vk-1,vk)，则松弛过后u.d = min_w(s,v)；``
Bellman Ford algorithm

The Bellman algorithm solves the single-source shortest path problem under normal circumstances, and the short-circuit of the edge can be negative
Applies to: There is a loop, the path weight is negative, but the figure cannot contain a loop with a negative weight.

Complexity of Time
``O(VE);外层循环为O(V),内层循环使用聚合分析得O(E);总的复杂度为:O(VE);``
Code:
``#include <iostream> #include <algorithm> #include <queue> #include <vector> #include <stack >using namespace std; #define INF 0x7fffffffstruct edge{int u,v,t;}; int n,t; Edge a[2002];int ans[1001];int pre[1001];void bellman_ford (int s) {for (int i = 1; I <= N; ++i) {Ans[i] =    INF;    } Pre[s] = 0;    Ans[s] = 0; int e1 = n-1;//number of cycles is vertex minus one; Because a shortest path contains up to N-1 edges; int e2 = t;//edge number; for (int i = 0; i < E1; ++i) {for        (int j = 0; j < E2; ++j)            {//The following is a relaxation operation on the edge, in order to prevent data overflow, have made many judgments.                The actual principle is very concise:/* int tmp = ANS[A[J].U] + a[j].t;                     if (TMP < ANS[A[J].V]) {ANS[A[J].V] = tmp;//Update to the short-circuit path value;            PRE[A[J].V] = a[j].u;//Update the predecessor node;} */if (ans[a[j].u] = = INF) continue;            int tmp = ANS[A[J].U] + a[j].t; if (ans[a[j].v] = = INF) {ANS[A[J].V] = TMP            PRE[A[J].V] = a[j].u;                } else if (TMP < ANS[A[J].V]) {ANS[A[J].V] = tmp;            PRE[A[J].V] = a[j].u;    }}}}int Main () {cin >> T >> N;    for (int i = 0; i < T; ++i) {cin >> a[i].u >> a[i].v >> a[i].t;        } bellman_ford (1);        outputs all shortest paths; for (int i = 1; I <= N; ++i) {int id = i;        Stack<int> St;            while (Pre[id]! = 0) {St.push (ID);        id = pre[id];        } st.push (ID);        cout << st.top ();        St.pop ();            while (!st.empty ()) {int tmp = St.top ();            St.pop ();        cout << "--" <<tmp;    } cout << Endl;   } return 0; }/*10 51 2 61 5 72 3 52 5 83 2-24 3 74 1 25 1 75 3-35 4 9*/``
SPFA (shortest Path Faster algorithm) algorithm

Use the queue to optimize for Bellman Ford:
Bellman Ford is the relaxation of each edge, in fact, every time only the shortest path of the last relaxation (d) the point at which the change can be reached is possible,
So, with a queue saved, the D value changes point, then the points in the queue, the related edges are relaxed.

Correctness of the algorithm:
``假定存在一条最短路径： 如果p(v0, v1, v2, ....vk,vk+1,.. , vM)为v0到vM 的最短路径，使用路径松弛定理进行证明，容易知道若某一次while循环松弛了边(vk-1,vk)，由于vk入队，则后续循环中当vk出队，则(vk,vk+1)边必会得到松弛，所以算法是正确的。``
Complexity of Time:
``O(k*E)，k的取值2-3（参考百度百科）``
Code
``#include <iostream> #include <algorithm> #include <queue> #include <vector> #include <stack    >using namespace std; #define INF 0x7fffffffstruct ed{int to,cost; Ed () {} ed (int a,int B): to (a), cost (b) {}};int n,t;vector<ed> a[1001];int ans[1001];int pre[1001];int VI    S[1001];void SPFA (int s) {for (int i = 1; I <= N; ++i) {ans[i] = INF;    } Pre[s] = 0;    Ans[s] = 0;    Vis[s] = 1;    Queue<int> Q;    Q.push (s);        while (!q.empty ()) {Int. now = Q.front ();        Q.pop ();        Vis[now] = 0;        int len = A[now].size ();            for (int i = 0; i < len; ++i) {int nt = a[now][i].to;            int wt = A[NOW][I].COST;            int tmp = Ans[now] + wt;                if (TMP < ANS[NT]) {ans[nt] = tmp;                PRE[NT] = now;                    if (vis[nt] = = 0) {q.push (NT);                Vis[i] = 1;     }       }}}}int Main () {cin >> T >> N;    int uu,vv,tt;        for (int i = 0; i < T; ++i) {cin >> UU >> vv >> tt;    A[uu].push_back (Ed (VV,TT));        } SPFA (1);        outputs all shortest paths; for (int i = 1; I <= N; ++i) {int id = i;        Stack<int> St;            while (Pre[id]! = 0) {St.push (ID);        id = pre[id];        } st.push (ID);        cout << st.top ();        St.pop ();            while (!st.empty ()) {int tmp = St.top ();            St.pop ();        cout << "--" <<tmp;    } cout << Endl;   } return 0; }/*10 51 2 61 5 72 3 52 5 83 2-24 3 74 1 25 1 75 3-35 4 9*/``
Dijkstra algorithm
``Dijkstra 算法解决的是带权图的有向图的最短路径问题，要求w(u,v) >= 0;``
Pseudo code:
``集合S为顶点最短路径值已知的点； 集合V为所有顶点的集合；  Dijkstra(int s){    1.初始化;将所有点的最短路径估计值设为INF;     2.将源节点的最短路径值设为0.    当S != V 时，执行如下操作：         1.在 V - S中找到最短路径估计值最小的顶点u,加入集合S.         2.对 u 的所有相邻节点的进行松弛操作Relax. }算法导论伪代码：    集合S为顶点最短路径值已知的点；     集合V为所有顶点的集合；     最小优先队列Q用于保存集合 V - S;     Dijkstra(int s){    1.初始化;将所有点的最短路径估计值设为INF;     2.将源节点的最短路径值设为0.    while Q != empty        u = Extract_min(Q); 在 Q中找到最短路径估计值最小的顶点u        S = S U {u};        for 节点 u 的每个可达节点 v            Relax(u,v,w); }``
Complexity of Time
``    O((V+E)lg(V));{主要参考算法导论}``
Code implementation
``#include <iostream> #include <algorithm> #include <queue> #include <vector>using namespace std;     #define N 201#define INF 0x7fffffffstruct ed{int to,cost;//represent the ordinal and edge weights of the next node reached, respectively, Ed (int a,int b): to (a), cost (b) {    } Ed () {}};struct nod{int id,d; Nod (int id_,int d_): ID (id_), D (d_) {} Nod () {}};struct cmp{//is used for precedence of nodes in priority queue comparison; bool operator () (NOD&A    MP;A,NOD&AMP;B) {return A.D > b.d;     }};vector<ed> a[n];int ans[n];void Dijkstra (int s) {for (int i = 1; I <= N; ++i) {ans[i] = INF;    } priority_queue<nod,vector<nod>,cmp> Q;    Ans[s] = 0;    Q.push (Nod (s,0));        while (!q.empty ()) {Nod now = Q.top ();        Q.pop ();        int id = now.id;        int d = NOW.D;        if (Ans[id] < D) continue;//discovers that the node has been relaxed after entering the priority queue, skipping directly; int len = A[id].size ();        int nt,w;            for (int i = 0; i < len; ++i) {NT = a[id][i].to; W = a[id][i].cost;            int tmp = d + W;                if (TMP < ANS[NT]) {ans[nt] = tmp;            Q.push (Nod (nt,tmp)); }        }    }}``
Example Exercises

Til the Cows Come Home
Frogger
Heavy Transportation
More Exercises

Single Source Shortest Path algorithm

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.