[洛谷1135]奇怪的电梯

题目描述

呵呵,有一天我做了一个梦,梦见了一种很奇怪的电梯。大楼的每一层楼都可以停电梯,而且第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。

输入输出样例

输入样例#1:

LIFT.IN
5 1 5
3 3 1 2 5

输出样例#1:

LIFT.OUT
3

思路

  好像是递推的样子,然而我不会写,于是怒写一个搜索,结果过了,过了。

var s:array[1..2010]of longint;  
    f:array[1..2010]of boolean;  
    ff:boolean;  
    i,n,q,z,ans:longint;  
  
function minx(x,y:longint):longint;  
begin  
    if x<y then exit(x) else exit(y);  
end;  
  
procedure DFS(x,min:longint);  
var h:longint;  
begin  
    if x=z then  
        begin  
            ans:=minx(min,ans);  
            exit;  
        end;  
     for h:=1 to 2 do  
        begin  
            if (min>ans)and(ans<>300000) then exit;  
            if h=1 then  
                begin  
                    if (x+s[x]>0)and(x+s[x]<n+1)and(f[x+s[x]]) then  
                        begin  
                            f[x+s[x]]:=false;  
                            dfs(x+s[x],min+1);  
                            f[x+s[x]]:=true;  
                        end;  
                end  
  
            else  
                if h=2 then  
                    begin  
                        if (x-s[x]>0)and(x-s[x]<n+1)and(f[x-s[x]])then  
                            begin  
                                f[x-s[x]]:=false;  
                                dfs(x-s[x],min+1);  
                                f[x-s[x]]:=true;  
                            end;  
                    end;  
        end;  
     if min>1000 then  
        begin  
            ff:=false;  
            exit;  
        end;  
end;  
  
begin  
    fillchar(f,sizeof(f),true);  
    ff:=true;  
    readln(n,q,z);  
    for i:=1 to n do read(s[i]);  
    ans:=maxint;  
    dfs(q,0);  
    if ans=maxint then  
        begin  
            writeln(-1);  
            halt;  
        end;  
    if ff then writeln(ans) else writeln(-1);  
end.  
View Code
原文地址:https://www.cnblogs.com/yangqingli/p/4886998.html