【模板】单源最短路径

SPFA

#include<bits/stdc++.h>

using namespace std;

const int oo = 2147483647;
const int N = 10010;
const int M = 500010;

int n, m, s, e;
int dis[N], vis[N];
int to[M*2], nxt[M*2], wht[M*2], begin[N];

template <typename T>
T read(){
    T N(0), F(1);
    char C = getchar();
    for(; !isdigit(C); C = getchar()) if(C == '-') F = -1;
    for(; isdigit(C); C = getchar()) N = N*10 + C-48;
    return N*F;
}

void add(int x, int y, int z){
    to[++e] = y; nxt[e] = begin[x]; wht[e] = z; begin[x] = e;
//    to[++e] = x; nxt[e] = begin[y]; wht[e] = z; begin[y] = e;
}

void init(){
    for(int i = 1; i <= n; i++) dis[i] = oo, vis[i] = 1;
    dis[s] = vis[s] = 0;
}

queue<int> Q;
void spfa(){
    Q.push(s);
    while(!Q.empty()){
        int u = Q.front();
        Q.pop(); vis[u] = 1;
        for(int i = begin[u]; i; i = nxt[i]){
            int v = to[i], w = wht[i];
            if(dis[u] + w < dis[v]){
                dis[v] = dis[u] + w;
                if(vis[v]){
                    Q.push(v);
                    vis[v] = 0;
                }
            }
        }
    }
}

int main(){
    n = read<int>(); m = read<int>(); s = read<int>();
    for(int i = 1; i <= m; i++){
        int x, y, z;
        x = read<int>(); y = read<int>(); z = read<int>();
        add(x, y, z);
    }

    init(); 
    spfa();

    for(int i = 1; i <= n; i++) printf("%d ", dis[i]);

    return 0;
}
原文地址:https://www.cnblogs.com/hanser/p/7684110.html