Strange elevator, strange elevator
§Strange elevator(Lift. cpp)§[Problem description]§ The elevator is available on each floor of the building, and a digital Ki (0 <= Ki <= N) is available on floor I (1 <= I <= N ). The elevator has only four buttons: On, off, up, down. The upper and lower layers are equal to the number on the current floor. Of course, if the requirements cannot be met, the corresponding button will fail. For example, 3 3 1 2 5 represents Ki (K1 = 3, K2 = 3 ,......), From the first floor. On the first floor, you can press "up" to go to the fourth floor. clicking "down" does not work because there is no-2 floor. How many buttons should be pushed from building A to Building B? §[Input format]Lift. in § the input file contains two rows. The first row contains three positive integers separated by spaces, indicating N, A, and B (1 ≤ N ≤ 200, 1 ≤ A, B ≤ N ), the second act is N positive integers separated by spaces, representing Ki. §[Output format]Lift. out § only one line of output file, that is, the minimum number of buttons. If it cannot be reached,-1 is output. §[Input example]§ 5 1 5 § 3 3 1 2 5 §[Output example]§ 3
1 #include<iostream> 2 using namespace std; 3 int lc[1000001]; 4 int tot=10001; 5 int n; 6 int beginn; 7 int endn; 8 void dfs(int now,int step) 9 {10 if(now==endn)11 {12 if(step<tot)13 tot=step;14 return;15 }16 else17 {18 if(now-lc[now]>0)19 {20 dfs(now-lc[now],step+1);21 }22 if(now+lc[now]<=n)23 {24 dfs(now+lc[now],step+1);25 }26 }27 }28 int main()29 {30 31 cin>>n>>beginn>>endn;32 for(int i=1;i<=n;i++)33 {34 cin>>lc[i];35 }36 dfs(beginn,0);37 if(tot!=10001)cout<<tot;38 else 39 {40 cout<<-1;41 }42 return 0;43 }