poj 3255

#include <iostream>
#include <cstdio>
#include <cstring>
#include <set>
#include <algorithm>
#include <map>
#include <queue>
#include<vector>
#define maxn 5010
#define maxm 12500010
#define INF 0x3fffffff
using namespace std;
struct edge {
     int to,w;
     edge(){}
     edge(int _to,int _w){
        to=_to;w=_w;
     }
 };
typedef pair<int,int> P;
int V;
 vector<edge> G[maxn];
 int d[maxn];//最短路
 int d2[maxn];//次短路
 void dijkstra(int s){
    priority_queue<P,vector<P>,greater<P> >q;
     for(int i=0;i<V;++i){
         d[i]=INF;
         d2[i]=INF;
     }
     d[s]=0;
     q.push(P(d[s],s));
     while(!q.empty()){
         P p = q.top();
         q.pop();
         int v = p.second,c=p.first;
         if(d2[v]<p.first)continue;
         for(int i=0;i<G[v].size();++i){
             edge e = G[v][i];
            int c2 = c+e.w;//新的权值
             if(d[e.to]>c2){//维护最短路
                 swap(d[e.to],c2);
                 q.push(P(d[e.to],e.to));
             }
            if(d2[e.to]>c2&&d[e.to]<c2){//维护次短路
                 d2[e.to]=c2;
                 q.push(P(d2[e.to],e.to));
             }
         }
     }
 }
 int main (){
     int n,m;
     while(scanf("%d%d",&n,&m)!=EOF){
         for(int i=0;i<n;++i)G[i].clear();
         V=n;
         if(n==0&&m==0)break;
         int u,v,w;
         for(int i=0;i<m;++i){
             scanf("%d%d%d",&u,&v,&w);
             G[u-1].push_back(edge(v-1,w));
             G[v-1].push_back(edge(u-1,w));
         }
         dijkstra(0);
         printf("%d\n",d2[n-1]);
     }
 }

posted @ 2016-09-24 13:43  StevenLuke  阅读(133)  评论(0编辑  收藏  举报