Codeforces 601A The Two Routes(最短路徑)
The Two Routes
time limit per test 2 seconds memory limit per test 256 megabytes input standard input output standard outputIn Absurdistan, there are
n towns (numbered1 through
n) andm bidirectional railways. There is also an absurdly simple road network — for each pair of different townsx andy, there
is a bidirectional road between townsx
A train and a bus leave town
1 at the same time. They both have the same destination, town
n, and don't make any stops on the way (but they can wait in townn
You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train
and the bus must not arrive at the same town (except town
n
Under these constraints, what is the minimum number of hours needed for both vehicles to reach townn (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the townn at the same moment of time, but are allowed to do so.
InputThe first line of the input contains two integersn andm (2 ≤ n ≤ 400,0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively.
Each of the next m lines contains two integersu andv, denoting a railway between townsu andv (1 ≤ u, v ≤ n,u ≠ v).
You may assume that there is at most one railway connecting any two towns.
OutputOutput one integer — the smallest possible time of the later vehicle's arrival in townn. If it's impossible for at least one of the vehicles to reach townn, output - 1.
Examples Input4 2
1 3
3 4
Output
2
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
Input
5 5
4 2
3 5
4 5
5 1
1 2
Output
3
Note
In the first sample, the train can take the route and the bus can take the route. Note that they can arrive at town4 at the same time.
In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town4.
題意:
兩種交通工具,題目給出鐵路的路徑,剩下的路徑為公路,問兩種交通工具都到達n所需的最少時間。
分析:
肯定有一種交通工具能直接從1到達n,則求的時間就是另一種交通工具從1到達n的最短路徑。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
int n,m,map[405][405],a,b,can,d[405],in[405],ve[405],begin=0,end=0,x;
memset(map,0,sizeof(map));
memset(in,0,sizeof(in));
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++){
scanf("%d%d",&a,&b);
map[a][b]=1;
map[b][a]=1;
}
if(map[1][n])can=0;
else can=1;
//printf(" can %d\n",can);
ve[end++]=1;
in[x]=1;
for(int i=2;i<=n;i++){
d[i]=10000;
}
d[1]=0;
while(begin!=end){
x=ve[begin++];
//printf("%d\n",x);
begin%=400;
in[x]=0;
for(int i=1;i<=n;i++){
if(map[x][i]==can){
if(d[i]>d[x]+1){
d[i]=d[x]+1;
//printf(" i %d d %d",i,d[i]);
if(!in[i]){
ve[end++]=i;
end%=400;
in[i]=1;
}
}
}
}
}
if(d[n]==10000)printf("-1\n");
else printf("%d\n",d[n]);
return 0;
}