最短路 - dijkstra

https://www.luogu.org/problem/P4779

给定一个 NN 个点,MM 条有向边的带非负权图,请你计算从 SS 出发,到每个点的距离。


 

本来做的次短路的题,顺便重新A了一遍这个

#include<iostream> 
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>

#define ri register int
#define u int
#define NN 100005
#define MM 200005

namespace fast {
    inline u in() {
        u x(0);
        char s=getchar();
        while(s<'0'||s>'9') {
            s=getchar();
        }
        while(s>='0'&&s<='9') {
            x=(x<<1)+(x<<3)+s-'0';
            s=getchar();
        }
        return x;
    }
}

using fast::in;

namespace all {
    u cnt,N,M,d[2][NN],h[NN];
    struct node {
        u to,next,va;
    } a[MM<<1]; 
    inline void add(const u &x,const u &y,const u &z) {
        a[++cnt].next=h[x],a[cnt].to=y,a[cnt].va=z,h[x]=cnt;
    }
    
    typedef std::pair<u,u> p;
    std::priority_queue<p,std::vector<p>,std::greater<p> > q;
    
    void dj(const u &x){
        std::memset(d,0x3f,sizeof(d));
        q.push(p(0,x)),d[0][x]=0;
        while(!q.empty()){
            u _x(q.top().second),_dic(q.top().first);
            q.pop();
            if(d[1][_x]<=_dic) continue;
            for(ri i(h[_x]);i;i=a[i].next){
                u _y(a[i].to),_z(a[i].va+_dic);
                if(d[0][_y]>_z){
                    std::swap(d[0][_y],_z);
                    q.push(p(d[0][_y],_y));
                }
                if(d[1][_y]>_z&&_z>d[0][_y]){
                    std::swap(d[1][_y],_z);
                    q.push(p(d[1][_y],_y));
                }
            }
        }
    }
    
    inline void solve(){
        u S;
        N=in(),M=in(),S=in();
        for(ri i(1);i<=M;++i){
            u _a(in()),_b(in()),_c(in());
            add(_a,_b,_c);//,add(_b,_a,_c);
        }
        dj(S);
        for(ri i(1);i<=N;++i){
            printf("%d ",d[0][i]);
        }
    }
}

int main() {
    //freopen("x.txt","r",stdin);
    //freopen("my.txt","w",stdout);
    all::solve();
}

 

posted @ 2019-10-04 10:41  pai_hoo  阅读(145)  评论(0编辑  收藏  举报