zoukankan      html  css  js  c++  java
  • 【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;
    }
  • 相关阅读:
    套接字(socket)
    网络编程
    面向对象之反射
    面向对象的多态
    面向对象之封装
    面向对象之继承
    面向对象之编程思想
    python中的包
    python中的序列化模块
    正则表达式
  • 原文地址:https://www.cnblogs.com/gwj1314/p/9444838.html
Copyright © 2011-2022 走看看