【20170706】次短路

图的次短路(求最短路时顺带求一下):

#include<iostream>
#include<vector>
#include<cstdio>
#include<queue>
#define INF 0x7fffffff
#define Max_v 5005
using namespace std;
struct edge{int to,cost;};
typedef pair<int,int> P;
int n,m;
vector <edge> G[Max_v];
int d[Max_v],d2[Max_v];
void dijstra(){     
    priority_queue<P,vector<P>,greater<P> >que;
    fill(d+1,d+n+1,INF); fill(d2+1,d2+n+1,INF);
    d[1]=0; que.push(P(0,1));
    while(!que.empty()){
        P p=que.top();que.pop(); 
        int v=p.second,dd=p.first;
        if(d2[v]<dd) continue;
        for(int i=0;i<G[v].size();i++){
            edge e=G[v][i];
            int d_2=dd+e.cost;
            if(d[e.to]==d_2||d_2==d2[e.to]) continue;
            if(d[e.to]>d_2){
                d2[e.to]=d[e.to];
                d[e.to]=d_2;
                que.push(P(d[e.to],e.to));
                que.push(P(d2[e.to],e.to));
            }
            if(d_2<d2[e.to]&&d_2>d[e.to]){
                d2[e.to]=d_2;
                que.push(P(d2[e.to],e.to));
            }
        }
    }
}
int main(){
    int x,y,w,minn=INF;
    scanf("%d%d",&n,&m);
    for(int i=0;i<m;i++){
        scanf("%d%d%d",&x,&y,&w);
        minn=min(minn,w);
        edge e={y,w};
        G[x].push_back(e);
        e={x,w};
        G[y].push_back(e);
    }
    dijstra();
    printf("%d",d2[n]);
    return 0;
}

——————————————————————————————————————

来自Paper Cloud的博客,未经允许,请勿转载,谢谢。

posted @ 2017-07-06 23:22  PaperCloud  阅读(188)  评论(0编辑  收藏  举报