SPFA最短路径 路径记录

做了一道板子题,求v0点到任意点的最短距离和最短路径

这里用SPFA,记录一下

#include 
#define MAXN 500005

using namespace std;
typedef long long ll;

struct Edge{
    ll next, weight;
    
    Edge(ll _next, ll _weight){
        next = _next;
        weight = _weight;
    }
};

vector g[MAXN];//邻接表

ll n, m;
ll dis[MAXN], vis[MAXN];
ll pre[MAXN];

void spfa(ll s){
    queue q;
    for(ll i = 0; i <= MAXN; i++)
        dis[i] = MAXN << 4;
    memset(vis, 0, sizeof vis);
    q.push(s);
    vis[s] = 1;
    dis[s] = 0;
    while(!q.empty()){
        ll u = q.front();
        q.pop();
        vis[u] = 0;
        for(ll i = 0; i < g[u].size(); i++){
            ll v = g[u][i].next;
            if(dis[v] > dis[u] + g[u][i].weight){
                dis[v] = dis[u] + g[u][i].weight;
                pre[v] = u;//记录前驱
                if(!vis[v]){
                    vis[v] = 1;
                    q.push(v);
                }
            }
        }
    }
}

int main(){
    scanf("%lld %lld", &n, &m);
    ll a, b, v;
    for(ll i = 0; i < m; i++){
        scanf("%lld %lld %lld", &a, &b, &v);
        g[a].push_back(Edge(b, v));
        g[b].push_back(Edge(a, v));//无向图双向保存
    }
    for(ll i = 1; i < n; i++){
        printf("v0 to v%lld\n", i);
        memset(pre, 0, sizeof pre);
        spfa(i);//从终点反向跑spfa
        printf("Length: %lld\n", dis[0]);
        printf("Path: \n");
        ll j = 0;
        printf("0");
        while(j != i){
            printf("->%lld",pre[j]);
            j=pre[j];
        }
        printf("\n\n");
    }
    return 0;
}

你可能感兴趣的:(acm)