题目链接:http://poj.org/problem?id=3255(《挑战》)
题意:就是求1到n的次短路
思路:同时求出最短路和次短路,如何判断次短路呢?要么就是1到某个非终点的u的最短路,再加上d(u ,v ),要么是1到某个非终点的u的次短路,再加上d(u ,v ),只有这两种可能
(具体可以看代码的注释)
代码:
#include <cstdio>
#include <cmath>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <numeric>
#include <set>
#include <string>
#include <cctype>
#include <sstream>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long LL;
typedef pair<int, int> P;
const int maxn = 5e3 + 5;
int n,r;
struct edge{
int to,cost;
};
vector<edge>G[maxn];
int d[maxn];
int dd[maxn];
void dijk(){
priority_queue<P,vector<P>,greater<P> >q;
memset(d,INF,sizeof(d));
memset(dd,INF,sizeof(dd));
d[1]=0;
q.push(P(0,1));
while (!q.empty()){
P p=q.top();
q.pop();
int v=p.second,dis=p.first;
if (dd[v]<dis) continue;//舍弃被次短路还大的值
for (int i=0;i<G[v].size();i++){
edge e=G[v][i];
int d2=dis+e.cost;
if (d[e.to]>d2){
swap(d[e.to],d2); //更新最短路
q.push(P(d[e.to],e.to));
}
if (dd[e.to]>d2&&d[e.to]<d2){ //长度在最短路和次短路之间则可以更新次短路
dd[e.to]=d2;
q.push(P(dd[e.to],e.to));
}
}
}
}
int main () {
//freopen ("in.txt", "r", stdin);
while (~scanf ("%d%d",&n,&r)){
int u,v,c;
while (r--){
scanf ("%d%d%d",&u,&v,&c);
G[u].push_back(edge{v,c});
G[v].push_back(edge{u,c});
}
dijk();
printf ("%d\n",dd[n]);
}
return 0;
}