POJ

https://vjudge.net/problem/POJ-3255

求1到n的次短路


就在dj上改一下,有些细节注意

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

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

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]){//这里一点要判_z>d[0][_y] 
                    std::swap(d[1][_y],_z);
                    q.push(p(d[1][_y],_y));
                }
            }
        }
    }
    
    inline void solve(){
        N=in(),M=in();
        for(ri i(1);i<=M;++i){
            u _a(in()),_b(in()),_c(in());
            add(_a,_b,_c),add(_b,_a,_c);
        }
        dj(1);
        printf("%d ",d[1][N]);
    }
}

int main() {
    //freopen("x.txt","r",stdin);
    //freopen("my.txt","w",stdout);
    all::solve();
}
原文地址:https://www.cnblogs.com/ling-zhi/p/11621752.html