正题
大意
一张无向图,求次短路。
解题思路
我们先求出最短路并且求出点1和点n到每个点的距离,然后枚举边,将第一个点离点1的距离,和第二个点离点n的距离加上边权如果不是最短路就记录,然后取最小值。
IOI赛制不需要证明正确性
代码
#include<cstdio>
#include<queue>
#include<cstring>
#define MN 5010
using namespace std;
queue<int> q;
struct line{
int from,to,w,next;
}a[300010];
int n,m,tot,x,y,w,f[MN],ls[MN],len[MN],f2[MN],ans;
bool v[MN];
void addl(int x,int y,int w)
{
a[++tot].from=x;a[tot].to=y;
a[tot].w=w;a[tot].next=ls[x];ls[x]=tot;
}
void spfa()
{
memset(f,127/3,sizeof(f));
q.push(1);v[1]=1;
f[1]=0;
while (!q.empty())
{
int x=q.front();
q.pop();v[x]=0;
for (int i=ls[x];i;i=a[i].next)
{
int y=a[i].to;
if (f[x]+a[i].w<f[y])
{
f[y]=f[x]+a[i].w;
if (!v[y])
{
v[y]=1;
q.push(y);
}
}
}
}
}
void spfa1()
{
memset(f2,127/3,sizeof(f2));
q.push(n);v[n]=1;
f2[n]=0;
while (!q.empty())
{
int x=q.front();
q.pop();v[x]=0;
for (int i=ls[x];i;i=a[i].next)
{
int y=a[i].to;
if (f2[x]+a[i].w<f2[y])
{
f2[y]=f2[x]+a[i].w;
if (!v[y])
{
v[y]=1;
q.push(y);
}
}
}
}
}
int main()
{
freopen("block.in","r",stdin);
freopen("block.out","w",stdout);
scanf("%d%d",&n,&m);
for (int i=1;i<=m;i++)
{
scanf("%d%d%d",&x,&y,&w);
addl(x,y,w);addl(y,x,w);//加边
}
spfa();spfa1();//两遍SPFA
int shest=f[n];//记录最短路
ans=2147483647;
for (int i=1;i<=tot;i++)
if (f[a[i].from]+f2[a[i].to]+a[i].w>shest&&f[a[i].from]+f2[a[i].to]+a[i].w<ans)
ans=f[a[i].from]+f2[a[i].to]+a[i].w;//记录答案
printf("%d",ans);
}