• SPFA 最短路径打印方法


    #include <iostream>
    #include <cstdlib>
    #include <cstdio>
    #include <algorithm>
    #include <vector>
    #include <queue>
    #include <cmath>
    #include <cstring>
    using namespace std;
    #define INF 0xfffffff
    #define maxn 40
    
    struct Edge
    {
        int e, w;
        Edge(int e=0,int w=0) : e(e), w(w) {}
    };
    int Path[maxn], n, dist[maxn];
    bool vis[maxn];
    vector<Edge> G[maxn];
    
    void Spfa(int Star,int End)
    {
        Edge P, Pn;
        dist[Star] = 0;
        queue<Edge> Q;
        Q.push(Edge(Star,0));
    
        while( !Q.empty() )
        {
            P = Q.front();
            Q.pop();
            vis[P.e] = true;
    
            int len = G[P.e].size();
    
            for(int i=0; i<len; i++)
            {
                Pn = G[P.e][i];
    
                if(dist[Pn.e] > dist[P.e] + Pn.w)
                {
                    dist[Pn.e] = dist[P.e] + Pn.w;
                    Path[Pn.e] = P.e;
                    if( !vis[Pn.e] )
                    {
                        Q.push(Pn);
                        vis[Pn.e] = true;
                    }
                }
            }
        }
    }
    
    void PutPath(int Star,int End)
    {
        if(Star == End)
        {
            printf("%d", Star);
            return ;
        }
    
        PutPath(Star, Path[End]);
    
        printf("---->%d", End);
    }
    void Init()
    {
        for(int i=1; i<=n; i++)
        {
            G[i].clear();
            dist[i] = INF;
            vis[i] = false;
            Path[i] = i;
        }
    }
    
    int main()
    {
        int m;
        cin >> n >> m;
    
        Init();
    
        for(int i=1; i<=m; i++)
        {
            int a, b, c;
            cin >> a >> b >> c;
            G[a].push_back(Edge(b,c));
        }
    
        Spfa(1, n);
    
        printf("%d
    ", dist[n]);
    
        PutPath(1,n);
    
    
    
        return 0;
    }
    /*
    4 3
    1 2 1
    2 3 1
    3 4 1
    */
  • 相关阅读:
    Objective-C 复合
    useContext的使用
    context的使用
    redux使用(二)
    redux使用(一)
    React class & function component 的区别
    combineReducers使用
    gnvm使用(未使用成功)
    React相关知识点
    eslint简单使用&&eslint与webpack结合使用
  • 原文地址:https://www.cnblogs.com/chenchengxun/p/4173441.html
Copyright © 2020-2023  润新知