求次短路,先求出1到所有点的距离dist,再求出N到所有点的距离dist[1],然后遍历所有边 dist[u]+cost[u][v]+dist1[v]第二的就是次短路。
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<utility>
#include<string.h>
#include<queue>
#include<vector>
using namespace std;
const int INF=0x3f3f3f3f;
typedef pair<int,int> P;
struct edge
{
int to;
int cost;
}e[300003];
vector<edge> G[6002];
int dist[6002];
int dist2[6002];
int ans[200003];
priority_queue < P, vector<P> , greater<P> > q;
int i,j,k;
void dij(int s,int * d)
{
while(!q.empty())
q.pop();
for(i=0;i<5001;i++)
d[i]=INF;
d[s]=0;
q.push(P(0,s));
P tp;
int f;
while(!q.empty())
{
tp=q.top();
q.pop();
f=tp.second;
if(d[f]<tp.first)
continue;
for(i=0;i<G[f].size();i++)
{
edge &te=G[f][i];
if(d[te.to]>d[f]+te.cost)
{
d[te.to]=d[f]+te.cost;
q.push(P(d[te.to],te.to));
}
}
}
}
int main()
{
int n,r,f;
scanf("%d%d",&n,&r);
for(i=0;i<r;i++)
{
scanf("%d%d%d",&f,&e[i].to,&e[i].cost);
G[f].push_back(e[i]);
e[i+r].to=f;
e[i+r].cost=e[i].cost;
G[e[i].to].push_back(e[i+r]);
}
dij(1,dist);
dij(n,dist2);
k=0;
for(i=1;i<=n;i++)
{
for(j=0;j<G[i].size();j++)
{
edge &te=G[i][j];
ans[k++]=dist[i]+te.cost+dist2[te.to];
}
}
sort(ans,ans+k);
int st=ans[0];
for(i=0;ans[i]==st;i++);
printf("%d\n",ans[i]);
}