贴一道利用优先队列实现的Dijkstra算法。这道题是要求次短路,所以对Dijkstra算法略作修改,同时保存最短和次短路数组。
#include<cstdio> #include<iostream> #include<vector> #include<queue> #include<functional> //#include<xutility> using namespace std; struct Edge{ long long cost; int to; Edge(long long co, int t):cost(co),to(t){} }; typedef pair< long long, int > P; int main() { int r,n; const long long INF=1000000000; scanf("%d%d",&n,&r); vector<Edge> *edge=new vector<Edge>[n+1]; long long *d=new long long [n+1]; long long *d1=new long long [n+1]; for(int i=0;i<r;i++) { int a,b; long long cost; scanf("%d%d%lld",&a,&b,&cost); edge[a].push_back(Edge(cost,b)); edge[b].push_back(Edge(cost,a)); } priority_queue< P, vector<P>, greater<P> > que; fill(d+1,d+n+1,INF); fill(d1+1,d1+n+1,INF); d[1]=0; que.push(make_pair(0,1)); while(!que.empty()) { P p=que.top(); que.pop(); int v=p.second; if(d1[v]<p.first) continue; for( int i=0;i<edge[v].size();i++) { Edge e = edge[v][i]; long long dTmp=p.first+e.cost; if(d[e.to]>dTmp){ swap(d[e.to],dTmp); que.push(make_pair(d[e.to],e.to)); } if(d1[e.to]>dTmp && d[e.to]<dTmp) { d1[e.to]=dTmp; que.push(make_pair(d1[e.to],e.to)); } } } cout<<d1[n]<<endl; return 0; }