求两次最短路,1到n
#include <bits/stdc++.h>
using namespace std;
int a[405][405],path[405],vis[405];
int main()
{
int n,m,x,y;
scanf("%d%d",&n,&m);
memset(a,0,sizeof(a));
for(int i=1;i<=m;i++)
{
scanf("%d%d",&x,&y);
a[x][y]=1;
a[y][x]=1;
}
int max1=0;
memset(vis,0,sizeof(vis));
path[1]=0;
for(int i=2;i<=n;i++)
if(a[1][i])path[i]=1;
else path[i]=n*5;
vis[1]=1;
for(int i=2;i<=n;i++)
{
int tmp,maxn;
tmp=1,maxn=5*n;
for(int j=2;j<=n;j++)
if(vis[j]==0&&path[j]<maxn)
{
tmp=j;maxn=path[j];
}
if(tmp==1)break;
vis[tmp]=1;
for(int j=1;j<=n;j++)
{
if(vis[j])continue;
if(a[tmp][j]==1&&path[j]>path[tmp]+1)
{
path[j]=path[tmp]+1;
}
}
}
if(path[n]>n){printf("-1\n");return 0;}
max1=path[n];
memset(vis,0,sizeof(vis));
path[1]=0;
for(int i=2;i<=n;i++)
if(a[1][i]==0)path[i]=1;
else path[i]=n*5;
vis[1]=1;
for(int i=2;i<=n;i++)
{
int tmp,maxn;
tmp=1,maxn=5*n;
for(int j=2;j<=n;j++)
if(vis[j]==0&&path[j]<maxn)
{
tmp=j;maxn=path[j];
}
if(tmp==1)break;
vis[tmp]=1;
for(int j=2;j<=n;j++)
{
if(vis[j])continue;
if(a[tmp][j]==0&&path[j]>path[tmp]+1)
{
path[j]=path[tmp]+1;
}
}
}
if(path[n]>n){printf("-1\n");return 0;}
max1=max(max1,path[n]);
cout<<max1<<endl;
return 0;
}