Shortest path: Dijkstra,bellman,spfa,floyd implementation of the algorithm

Source: Internet
Author: User




watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvdtaxmzq4nza1mq==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast "width=" "height=" >










watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvdtaxmzq4nza1mq==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast "width=" "height=" >





</pre><pre name= "code" class= "CPP" > #include <cstdio> #include <iostream> #include <cstring > #include <queue> #include <algorithm> #include <vector>using namespace Std;const int INF = 0x3f3f3f3f;//Infinity Const int MAXN = 20;//maximum number of vertices int n;//vertex number int edge[maxn][maxn];//adjacency matrix//dijkstra algorithm 3 array int s[maxn];/ /record whether vertices are in the collection int dist[maxn];//record path weights int path[maxn];//record path void Dijkstra (int v0)//Seek v0 to other points shortest path {int I, J, k;//loop variable fo        R (i=0; i<n; i++) {dist[i] = Edge[v0][i];        S[i] = 0;        if (i!=v0 && dist[i]<inf) path[i] = V0;    else Path[i] =-1; } S[v0] = 1;        Dist[v0] = 0;//Vertex v0 Add vertex set S for (i=0; i<n-1; i++)//from vertex v0 determine n-1 bar shortest path {int min = INF, u = v0;                Select the vertex with the shortest path in the current collection T U for (j=0; j<n; J + +) {if (!s[j] && dist[j]<min) {                U = j;            min = Dist[j]; }} S[u] = 1;//adds the vertex u to the set S. Indicates its shortest circuit.Dist and path array elements for (k=0; k<n; k++) {if (!s[k] && edge[u][k]<i) of the vertices in the T collection                    NF && Dist[u]+edge[u][k]<dist[k]) {dist[k] = Dist[u] + edge[u][k];                Path[k] = u;    }}}}int Main () {int i, j;//loop variable int u, V, start and end of w;//edge and weight scanf ("%d", &n);//read in vertex number n while (1)        {scanf ("%d%d%d", &u, &v, &w);        if (u==-1 && v==-1 && w==-1) break;                EDGE[U][V] = w;//building adjacency Matrix} for (i=0; i<n; i++) {for (j=0; j<n; J + +) {if (i==j)            EDGE[I][J] = 0;        else if (edge[i][j] = = 0) edge[i][j] = INF;        }} Dijkstra (0);//Find the shortest path of vertex 0 to other vertices int shortest[maxn];//The ordinal of each vertex on the output shortest path for (i=1; i<n; i++) { printf ("%d\t", Dist[i]);//output vertex 0 to vertex i shortest path length//The code below is used to output vertex 0 shortest path with vertex i memset (shortest, 0, sizeof (shorteST));        int k = 0;//k represents the subscript of the last element in the shorttest array shortest[k] = i;            while (path[Shortest[k]]!=0) {k++;            SHORTEST[K] = path[shortest[k-1]];        printf ("%d", k); } k++;        Shortest[k] = 0;        printf ("%d", k);        for (j=k; j>0; j--) printf ("%d--", Shortest[j]);    printf ("%d\n", shortest[0]); } return 0;}


Bellman:

#include <cstdio> #include <iostream> #include <cstring> #include <queue> #include < Algorithm> #include <vector>using namespace std;const int INF = 0x3f3f3f3f;const int maxn = 8;int EDGE[MAXN][MAXN]    ; int Dist[maxn];int path[maxn];int n;void Bellman (int v0) {int I, j, K, U;        for (i=0; i<n; i++) {dist[i] = Edge[v0][i];        if (i!=v0 && dist[i] < INF) Path[i] = V0;    else Path[i] =-1; } for (k=2, k<n; k++) {for (u=0; u<n; u++) {if (u!=v0) {f or (j=0; j<n; J + +) {if (Edge[j][u] < INF && Dist[j] + Edge[j][u] < di                        St[u]) {Dist[u] = Dist[j] + edge[j][u];                    Path[u] = j;    }}}}}}int main () {int i, J;    int U, V, W;    scanf ("%d", &n); while (1) {scanf ("%d%d%d", &u, &v, &w);         if (u==-1 && v==-1 && w==-1) break;    EDGE[U][V] = W;             } for (i=0; i<n; i++) {for (j=0; j<n; J + +) {if (i==j) edge[i][j] = 0;        else if (edge[i][j]==0) edge[i][j] = INF;    }} Bellman (0);    int SHORTEST[MAXN];        for (I=1; i<n; i++) {printf ("%d\t", Dist[i]);        memset (shortest, 0, sizeof (shortest));        int k = 0;        Shortest[k] = i;            while (path[shortest[k]]!=0) {k++;        SHORTEST[K] = path[shortest[k-1]];        } k++;        Shortest[k] = 0;        for (j=k; j>0; j--) printf ("%d--", Shortest[j]);    printf ("%d\n", shortest[0]); } return 0;}


SPFA:

#include <cstdio> #include <cstring> #include <queue> #define INF 1000000/Infinity # MAXN 10using Name    Space std;struct arcnode{int to;    int weight; struct Arcnode *next;};  Queue<int> Q;   The node in the queue is the vertex ordinal int n;  Number of vertices arcnode* LIST[MAXN];  Edge-Linked table header pointer for each vertex int INQ[MAXN];  Whether each vertex is a flag in the queue int DIST[MAXN]; int PATH[MAXN];  void spfa (int src) {int i, u;    U arcnode* temp for the queue overhead point ordinal;        for (i=0; i<n; i++)//Initialize {dist[i] = INF;        Path[i] = src;    Inq[i] = 0;    } DIST[SRC] = 0;    PATH[SRC] = src;    inq[src]++;    Q.push (SRC); while (!        Q.empty ()) {u = Q.front ();        Q.pop ();        inq[u]--;        temp = List[u];            while (temp!=null) {int v = temp->to;                if (Dist[v] > Dist[u] + temp->weight) {Dist[v] = Dist[u] + temp->weight;                PATH[V] = u;  if (!inq[v]) {Q.push (v);                  inq[v]++;        }} temp = temp->next;  }}}int Main () {int i, J;  loop variable int u, V, W;  The start and end point of the edge and the weight value scanf ("%d", &n);    Reads the number of vertices n memset (list, 0, sizeof (list));    arcnode* temp;  while (1) {scanf ("%d%d%d", &u, &v, &w);//start and end of read-in Edge if (u==-1 && v==-1 &&        W==-1) break;        temp = new Arcnode;        Construct adjacency Table temp->to = v;        Temp->weight = W;        Temp->next = NULL;        if (list[u]==null) list[u] = temp;            else {temp->next = List[u];        List[u] = temp; }} SPFA (0);        Find the shortest path to vertex 0 to other vertices for (j=0; j<n; j + +)//release the storage space occupied by each edge node on the edge list {temp = List[j];            while (Temp!=null) {List[j] = temp->next;            Delete temp;        temp = List[j];  }} int SHORTEST[MAXN];    The ordinal number of each vertex is stored for the output of each vertex on the shortest path for (i=1; i<n; i++) {    printf ("%d\t", Dist[i]);        The shortest path length of the output vertex 0 to vertex I//The code below is used to output the shortest path of vertex 0 to vertex i memset (shortest, 0, sizeof (shortest));  int k = 0;        K represents the subscript of the last element in the shortest array shortest[k] = i;            while (path[shortest[k]! = 0) {k++;        Shortest[k] = path[shortest[k-1]];        } k++;        Shortest[k] = 0;        for (j=k; j>0; j--) printf ("%d→", Shortest[j]);    printf ("%d\n", shortest[0]); } return 0;}


Floyd:


#include <cstdio> #include <iostream> #include <cstring> #include <queue> #include <   Algorithm> #include <vector>using namespace std; #define INF 1000000/Infinity # define MAXN 8int N;  Number of vertices int EDGE[MAXN][MAXN];    adjacency matrix int A[MAXN][MAXN];  int PATH[MAXN][MAXN];    void Floyd ()//assuming that the adjacency matrix and the number of vertices of the graph have been read in {int i, j, K;            For (i=0, i<n; i++) {for (j=0; j<n; J + +) {A[i][j] = edge[i][j];//to a[[] initialization if (i!=j && a[i][j]<inf) path[i][j] = i; I to J have path else path[i][j] =-1;    From I to J no direct path}}//from a (-1) to a (0), a (1), ..., a (n-1), or understood to be V0,v1,..., V (n-1) as the middle vertex for (k=0; k<n; k++) {for (i=0, i<n; i++) {for (j=0; j<n; J + +) {if (K==i | | k==j                ) continue;                    if (A[i][k] + a[k][j] < A[i][j]) {a[i][j] = A[i][k] + a[k][j];          PATH[I][J] = Path[k][j];      }}}}}int main () {int i, J;  loop variable int u, V, W;  The start and end point of the edge and the weight value scanf ("%d", &n);    Reads the number of vertices n for (i=0; i<n; i++)//sets the initial value of each element in the adjacency matrix to inf {for (j=0; j<n; j + +) edge[i][j] = inf;    } for (i=0; i<n; i++)//sets the value of the element on the diagonal of the adjacency matrix to 0 {edge[i][i] = 0; while (1) {scanf ("%d%d%d", &u, &v, &w);//The Start and end of the read-in Edge if (u==-1 && V==-1 &        & W==-1) break; EDGE[U][V] = W; Constructs adjacency matrix} Floyd (); Find the shortest path between the vertices int SHORTEST[MAXN]; The ordinal of each vertex is stored in the output of each vertex of the shortest path for (i=0; i<n; i++) {for (j=0; j<n; J + +) {if (I==J) CO Ntinue;  Skip printf ("%d=>%d\t%d\t", I, J, A[i][j]);            The shortest path length of the output vertex I to the vertex J//The code below is used to output the shortest path of vertex 0 to vertex i memset (shortest, 0, sizeof (shortest)); int k = 0;            K represents the subscript of the last element in the shortest array shortest[k] = j;       while (path[i][shortest[k]! = i) {         k++;            Shortest[k] = path[i][shortest[k-1]];            } k++;            Shortest[k] = i;            for (int t=k; t>0; t--) printf ("%d→", shortest[t]);        printf ("%d\n", shortest[0]); }} return 0;}




Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.

Shortest path: Dijkstra,bellman,spfa,floyd implementation of the algorithm

Contact Us

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.