poj——3255Roadblocks(优先队列 求最小次最短路径)

来源:互联网 发布:mac chili色号 编辑:程序博客网 时间:2024/06/05 05:27
Roadblocks
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 12152 Accepted: 4293

Description

Bessie has moved to a small farm and sometimes enjoys returning to visit one of her best friends. She does not want to get to her old home too quickly, because she likes the scenery along the way. She has decided to take the second-shortest rather than the shortest path. She knows there must be some second-shortest path.

The countryside consists of R (1 ≤ R ≤ 100,000) bidirectional roads, each linking two of the N (1 ≤ N ≤ 5000) intersections, conveniently numbered 1..N. Bessie starts at intersection 1, and her friend (the destination) is at intersection N.

The second-shortest path may share roads with any of the shortest paths, and it may backtrack i.e., use the same road or intersection more than once. The second-shortest path is the shortest path whose length is longer than the shortest path(s) (i.e., if two or more shortest paths exist, the second-shortest path is the one whose length is longer than those but no longer than any other path).

Input

Line 1: Two space-separated integers: N and R 
Lines 2..R+1: Each line contains three space-separated integers: AB, and D that describe a road that connects intersections A and B and has length D (1 ≤ D ≤ 5000)

Output

Line 1: The length of the second shortest path between node 1 and node N

Sample Input

4 41 2 1002 4 2002 3 2503 4 100

Sample Output

450

Hint

Two routes: 1 -> 2 -> 4 (length 100+200=300) and 1 -> 2 -> 3 -> 4 (length 100+250+100=450)

Source

USACO 2006 November Gold

#include<iostream>#include<string>#include<cstring>#include<queue>#include<vector>#include<cstdio>using namespace std; struct edge {int cost ;int to;};vector<edge> g[5005];typedef pair<int,int> p;int d1[5005];int d2[5005];int V,E;const int INF=100005;void dijkstra(){fill(d1,d1+V,INF);fill(d2,d2+V,INF);d1[0]=0;priority_queue<p,vector<p>,greater<p> > que;que.push(p(0,0));while(!que.empty()){p now=que.top();que.pop();int k=now.first;int v=now.second;//cout<<k<<"  "<<v<<endl;//cout<<d2[v]<<"  d2[v]"<<endl;//cout<<g[v].size()<<"  size"<<endl;if(d2[v]<k)continue;for(int i=0;i<g[v].size();i++){//cout<<g[v].size()<<"  size"<<endl;edge &e=g[v][i];int x=e.cost+k;if(d1[e.to]>x){//cout<<d1[e.to]<<"  "<<x<<endl;swap(d1[e.to],x);//cout<<d1[e.to]<<"  "<<x<<endl;que.push(p(d1[e.to],e.to));}if(d2[e.to]>x&&x>d1[e.to])//确认x比最小的边要大 并且d2要小于x  寻找次小边 {d2[e.to]=x;que.push(p(d2[e.to],e.to));}}}}int main(){cin>>V>>E;for(int i=0;i<E;i++){int k;int t,c;cin>>k>>t>>c;k=k-1;t=t-1;edge e1,e2;e1.to=t;e2.to=k;e1.cost=c;e2.cost=c; g[k].push_back(e1);g[t].push_back(e2);//由于是无向图  注意双向都可以走  不然会出错 }dijkstra();printf("%d\n",d2[V-1]);return 0;}


1 0
原创粉丝点击