【Luogu3371】【模板】单源最短路径(SPFA)

problem

  • 给出一个有向图
  • 求从某一点出发到所有点的最短路

solution

SPFA

codes

#include<iostream>
#include<queue>
#include<cstring>
#define maxn 10010
#define maxm 500010
using namespace std;

//Grape
int n, m, s;
struct Edge{int v, w, next;}e[maxm<<1];
int tot, head[maxn];
void AddEdge(int u, int v, int w){
    tot++; e[tot].v=v; e[tot].w=w; e[tot].next=head[u]; head[u]=tot;
}

//SPFA
int dist[maxn], book[maxn];
queue<int>q;
void spfa(){
    for(int i = 1; i <= n; i++)dist[i]=2147483647;
    dist[s]=0; book[s]=1; q.push(s);
    while(q.size()){
        int u = q.front();  q.pop();  book[u]=0;
        for(int i = head[u]; i > 0; i = e[i].next){
            int v = e[i].v, w = e[i].w;
            if(dist[v]>dist[u]+w){
                dist[v] = dist[u]+w;
                if(!book[v]){
                    book[v] = 1;  q.push(v);
                }
            }
        }
    }
}

int main(){
    cin>>n>>m>>s;
    for(int i = 1; i <= m; i++){
        int x, y, z; cin>>x>>y>>z; AddEdge(x,y,z);
    }
    spfa();
    for(int i = 1; i <= n; i++)
        cout<<dist[i]<<' ';
    return 0;
}
posted @ 2018-05-23 12:15  gwj1139177410  阅读(108)  评论(0编辑  收藏  举报
选择