Dijkstra water problem, is also suitable for the introduction of graph theory, pay attention to a few special cases can be, from the test instructions know any two villages must have a car or train direct, so only ask for a short circuit on the line. The other does not say directly on the code.
#include <bits/stdc++.h> using namespace std;
int dt[405][405],db[405][405],vis[405]={0},lowway[405],n,m;
#define INF 0x3f3f3f3f void Dijkstra (int d[][405]) {int i,j;
Vis[1]=1;
for (i=1;i<=n;i++) lowway[i]=d[1][i];
for (i=1;i<=n;i++) {int min=inf;
int k=0;
for (j=1;j<=n;j++) {if (!vis[j]&&lowway[j]<min) {min=lowway[j];
K=j;
}} vis[k]=1; for (j=1;j<=n;j++) {if (!vis[j]&&d[k][j]+lowway[k]<lowway[j]) lowway[j]=lowway[k
]+D[K][J];
}} if (Lowway[n]==inf) {cout<<-1<<endl;
return;
} else cout<<lowway[n]<<endl;
} int main () {int u,v,i,j;
memset (dt,0x3f,sizeof (DT));
memset (db,0x3f,sizeof (db));
memset (lowway,0x3f,sizeof (Lowway));
memset (vis,0,sizeof (VIS));
for (i=1;i<=n;i++) {dt[i][i]=db[i][i]=0; } cin>>n>>m;
for (i=1;i<=m;i++) {cin>>u>>v;
Dt[u][v]=dt[v][u]=1;
} for (i=1;i<=n;i++) for (j=1;j<=n;j++) if (dt[i][j]==inf) db[i][j]=db[j][i]=1;
if (m==n* (n-1)/2) cout<<-1<<endl;
else if (dt[1][n]==1) Dijkstra (db);
else Dijkstra (DT);
return 0;
}