【最短路】奇怪的电梯

来源:互联网 发布:理财模拟软件 编辑:程序博客网 时间:2024/04/29 10:04

题目:奇怪的电梯 rqnoj161

题目描述

呵呵,有一天ssxyh做了一个梦,梦见了一种很奇怪的电梯。大楼的每一层楼都可以停电梯,而且第i层楼(1<=i<=N)上有一个数字Ki(0<=Ki<=N)。电梯只有四个按钮:开,关,上,下。上下的层数等于当前楼层上的那个数字。当然,如果不能满足要求,相应的按钮就会失灵。例如:3 3 1 2 5代表了Ki(K1=3,K2=3,……),从一楼开始。在一楼,按“上”可以到4楼,按“下”是不起作用的,因为没有-2楼。那么,从A楼到B楼至少要按几次按钮呢?

输入格式

输入文件共有二行,第一行为三个用空格隔开的正整数,表示N,A,B(1≤N≤200, 1≤A,B≤N),第二行为N个用空格隔开的正整数,表示Ki。

输出格式

输出文件仅一行,即最少按键次数,若无法到达,则输出-1

样例输入

样例输出

 

读入数据后扫描一次就可以建图,然后dijkstra或者spfa都可以

Pascal Code

program lift;const maxn=200+10;var  n,a,b:longint;  map:array[0..maxn,0..maxn] of longint;  dist:array[0..maxn] of longint;  h:array[0..maxn] of boolean;procedure init;begin  assign(input,'rqnoj161.in');  assign(output,'rqnoj161.out');  reset(input);  rewrite(output);end;procedure outit;begin  close(input);  close(output);  halt;end;procedure readdata;var  i,k:longint;begin  fillchar(map,sizeof(map),$7);  read(n,a,b);  for i:=1 to n do  begin    map[i,i]:=0;    read(k);    if k=0 then continue;    if i+k<=n then map[i,i+k]:=1;    if i-k>0 then map[i,i-k]:=1;  end;end;procedure main;var  i,j,k,min:longint;begin  fillchar(dist,sizeof(dist),$7);  fillchar(h,sizeof(h),0);  dist[a]:=0;    for i:=1 to n do  begin    k:=0;min:=maxlongint;    for j:=1 to n do    begin      if (not h[j])and(dist[j]<min) then      begin        min:=dist[j];        k:=j;      end;    end;        h[k]:=true;        for j:=1 to n do    begin      if (not h[j])and(dist[j]>dist[k]+map[k,j]) then        dist[j]:=dist[k]+map[k,j];    end;  end;    if dist[b]=$07070707 then writeln(-1) else writeln(dist[b]);end;begin  init;  readdata;  main;  outit;end.