题意:求1到n的次短路径。
分析:dijistra算法,每次记录最短距离和次短距离。
#include <iostream>
#include<vector>
#include<queue>
#include<cstdio>
using namespace std;
#define N 10005
#define INF 0x7fffffff
struct edge
{
int to,cost;
edge(){}
edge(int x,int y)
{
to=x;
cost=y;
}
};
typedef pair<int,int>p;
int d[N];
int d1[N];
vector<edge>v[N];
void dijkstra(int s);
int n,r;
int main()
{
while(~scanf("%d%d",&n,&r))
{
for(int i=0;i<n;i++)
{
v[i].clear();
}
int a,b,c;
for(int i=0;i<r;i++)
{
scanf("%d%d%d",&a,&b,&c);
v[a-1].push_back(edge(b-1,c));
v[b-1].push_back(edge(a-1,c));
}
dijkstra(0);
printf("%d\n",d1[n-1]);
}
return 0;
}
void dijkstra(int s)
{
priority_queue<p,vector<p>,greater<p> >que;
fill(d,d+n,INF);
fill(d1,d1+n,INF);
d[s]=0;
que.push(p(0,s));
while(!que.empty())
{
p p1=que.top();
que.pop();
int dd=p1.first;
int t=p1.second;
if(dd>d1[t])continue;
for(int i=0;i<v[t].size();i++)
{
edge &e=v[t][i];
int d2=dd+e.cost;
if(d[e.to]>d2)
{
swap(d[e.to],d2);
que.push(p(d[e.to],e.to));
}
if(d1[e.to]>d2&&d[e.to]<d2)
{
d1[e.to]=d2;
que.push(p(d1[e.to],e.to));
}
}
}
}