算法:
题意求严格次短路,我们先跑SPFA,计算出从1和从N到其他各个点的最短路长度,接着枚举每一条边,可以O(1)算出N到1经过该边的最短路长度,我们统计出这2*R(双向道路)个长度中第二短的即可。
Code:
#include<iostream>
#include<queue>
#define rep(i,j,k) for(int i=j;i<=k;i++)
using namespace std;
template<typename T> void read(T &num){
char c=getchar();num=0;T f=1;
while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
while(c>='0'&&c<='9'){num=(num<<3)+(num<<1)+(c^48);c=getchar();}
num*=f;
}
template<typename T> void qwq(T x){
if(x>9)qwq(x/10);
putchar(x%10+'0');
}
template<typename T> void write(T x){
if(x<0){x=-x;putchar('-');}
qwq(x);putchar('\n');
}
template<typename T> void chkmin(T &x,T y){x=x<y?x:y;}
int N,R;
struct wzy{
int nxt,vertice,w;
}edge[200010];
int head[5010];int len=0;
inline void add_edge(int x,int y,int z){
edge[++len].nxt=head[x];edge[len].vertice=y;
edge[len].w=z;head[x]=len;return;
}
int dis[5010][2];
priority_queue<pair<int,int> >v;bool in[5010];
inline void SPFA(int st,int tmp){
rep(i,1,N){dis[i][tmp]=INT_MAX;in[i]=0;}
v.push(make_pair(0,st));in[st]=1;dis[st][tmp]=0;
while(!v.empty()){
int nop=v.top().second;in[nop]=0;v.pop();
for(int i=head[nop];i;i=edge[i].nxt){
int temp=edge[i].vertice;
if(dis[nop][tmp]+edge[i].w<dis[temp][tmp]){
dis[temp][tmp]=dis[nop][tmp]+edge[i].w;
if(!in[temp]){in[temp]=1;v.push(make_pair(-dis[temp][tmp],temp));}
}
}
}
return;
}
int main(){
read(N);read(R);
rep(i,1,R){
int u,v,c;read(u);read(v);read(c);
add_edge(u,v,c);add_edge(v,u,c);
}
SPFA(1,0);SPFA(N,1);
int ans=INT_MAX;
rep(i,1,N){
for(int j=head[i];j;j=edge[j].nxt){
if(dis[i][0]+dis[edge[j].vertice][1]+edge[j].w!=dis[N][0]){
chkmin(ans,dis[i][0]+dis[edge[j].vertice][1]+edge[j].w);
}
}
}
write(ans);
return 0;
}