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: A, B, 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 4
1 2 100
2 4 200
2 3 250
3 4 100
Sample Output
450
题意:求次短路的长度,dijkstra的简单变化,(PS:邻接表又写跪了,看了下书才改正确)
#include<cstdio>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
typedef pair<int,int>P;
const int maxn=5005;
const int INF=3e7;
struct edge{
int from,to,cost;
};
vector<edge>es[maxn];
int n,r;
int d1[maxn],d2[maxn];
void solve(){
fill(d1,d1+n,INF);
fill(d2,d2+n,INF);
d1[0]=0;
priority_queue<P,vector<P>,greater<P> >pq;
pq.push(P(0,0));
while(!pq.empty()){
P p=pq.top();
pq.pop();
int dis1=p.first,v=p.second;
if(d2[v]<dis1) continue;
for(int i=0;i<es[v].size();i++){
edge &e=es[v][i];
int dis2=dis1+e.cost;
if(d1[e.to]>dis2){
swap(d1[e.to],dis2);
pq.push(P(d1[e.to],e.to));
}
if(d2[e.to]>dis2&&d1[e.to]<dis2){
d2[e.to]=dis2;
pq.push(P(d2[e.to],e.to));
}
}
}
printf("%d\n",d2[n-1]);
}
void init(){
for(int i=0;i<n;i++){
es[i].clear();
}
}
void print(){
for(int i=0;i<n;i++){
for(int j=0;j<es[i].size();j++){
printf("%d %d %d\n",es[i][j].from,es[i][j].to,es[i][j].cost);
}
}
}
int main(){
//freopen("in.txt","r",stdin);
while(scanf("%d%d",&n,&r)>0){
//每次记得把vector数组情空
init();
for(int i=0;i<r;i++){
edge e;
scanf("%d%d%d",&e.from,&e.to,&e.cost);
e.from--;
e.to--;
es[e.from].push_back(e);
swap(e.from,e.to);
es[e.from].push_back(e);
}
//print();
solve();
}
return 0;
}