求次短路可以利用djistra的思想变化求得。
djistra求最短路,选出一个没用被确定集合中的一个距离最短的点,去更新相连的点。而次短路一定与最短路是不同的,例如:
1——2,权值为1;则1到2的最短路为1,次短路为3。a到b的次短路,一定会经过中间点c(可能是a,b),到c的最短路加上c->b,
或到c的次短路+c->b,因此不仅要求得最短路,还要记录次短路。
对于一个点,如果更新了最短路,则先前的最短路就是次短路,如果没有,找到一条比原来次短路短,但比最短路长的,更新次短路。
最好利用优先队列。要把次短路也加入到队列中,因为可能是c的次短路+c->b。
/*
poj 3255
*/
#include <stdio.h>
#include <algorithm>
#include <queue>
#include <vector>
#include <utility>
using namespace std;
struct edge
{
int to;
int cost;
};
#define MAX_N 5010
std::vector<edge> v[MAX_N];
int longst[MAX_N];
int second[MAX_N];
int n,r;
#define inf 9999999
typedef pair<int,int> p;
void se_path()
{
fill(longst,longst+MAX_N,inf);
fill(second,second+MAX_N,inf);
priority_queue<p,vector<p>,greater<p> > que;
que.push(p(1,0));
//longst[1]=0;
while(!que.empty())
{
p s=que.top();
que.pop();
int a=s.first;
int b=s.second;
if(second[a]<b) continue;
for(int i=0;i<v[a].size();i++)
{
edge &c=v[a][i];
int d=b+c.cost;
if(longst[c.to]>d)
{
swap(longst[c.to],d);
que.push(p(c.to,longst[c.to]));
}
if(second[c.to]>d && d>longst[c.to])
{
second[c.to]=d;
que.push(p(c.to,second[c.to]));
}
}
}
}
int main(int argc, char const *argv[])
{
//freopen("input","r",stdin);
// freopen("output1","w",stdout);
scanf("%d%d",&n,&r);
for(int i=0;i<r;i++)
{
int x,y,c;
scanf("%d%d%d",&x,&y,&c);
edge z;
z.to=y;
z.cost=c;
v[x].push_back(z);
z.to=x;
v[y].push_back(z);//注意是双向
}
se_path();
printf("%d\n",second[n] );
return 0;
}