计院有一个bug电梯,可能是hyk造的,很多bug,电梯只有两个按钮,“上”和“下”,电梯每层都可以停,每层都有一个数字Ki(0<=Ki<=n),当你在一层楼,你按“上”键会到1+K1层,你按“下”键会到1-K1层。当然,电梯不能升到N以上,也不能降到1以下。例如,有一个五层楼的建筑,k1=3,k2=3,k3=1,k4=2,k5=5。从第一层开始,你可以按“上”按钮,然后你就上到第四层,如果在第一层按“下”按钮,电梯就不能做到,因为你知道它不能下到负二层。负二楼不存在。
那么,你想从A层到B层,你至少要按多少次“上”或“下”按钮呢?Input输入由几个测试用例组成,每个测试用例包含两行。
第一行包含三个整数n,a,b(1<=n,a,b<=200),如上文所述,第二行包含n个整数k1,k2,….kn。
单个0表示输入的结束。
Output对于每种情况下的输入输出一个整数,当你在A层,你必须按下按钮的最少次数,你想去B层。如果你不能到达B层,打印“-1”。
Sample Input
5 1 5 3 3 1 2 5 0
Sample Output
3令人(我)费解的bfs,代码乱成一锅粥。每次可上可下,依次放入队列(实时更新?),判断边界且没有走过(不然会死循环)。
1 #include <iostream> 2 #include <queue> 3 #include <cstdio> 4 #include <cstring> 5 using namespace std; 6 int n,a,b; 7 int num[205]; 8 bool vis[205]; 9 struct node 10 { 11 int x;//当前位置 12 int step;//当前走的步数 13 } now,nextt; 14 int bfs(int x) 15 { 16 queue <node> q; 17 now.x = x;//现在的位置 初始化 18 now.step = 0;//现在的步数 初始化 19 q.push(now); 20 while(!q.empty()) 21 { 22 now = q.front();///现在的节点为队顶元素 23 q.pop();//弹出 24 if(now.x == b)//如果到达终点 25 return now.step; 26 nextt = now; 27 nextt.x = now.x + num[now.x];//下一个节点的位置为现在位置加上能走的步数 28 if(nextt.x >= 1 && nextt.x <= n && vis[nextt.x] == 0) 29 { 30 nextt.step = now.step + 1;//走的步数+1 31 vis[nextt.x] = 1; 32 q.push(nextt); 33 } 34 nextt.x = now.x - num[now.x];//下一个节点的位置为现在的位置减去能走的步数 35 if(nextt.x >= 1 && nextt.x <= n && vis[nextt.x] == 0) 36 { 37 nextt.step = now.step + 1;//走的步数+1 38 vis[nextt.x] = 1; 39 q.push(nextt); 40 } 41 } 42 return -1; 43 } 44 int main() 45 { 46 int sum = 0; 47 while (scanf ("%d",&n)&&n!=0){ 48 cin >> a >> b; 49 memset(num,0,sizeof(num)); 50 memset(vis,0,sizeof(vis)); 51 for(int i = 1; i <= n; i++) 52 cin >> num[i]; 53 sum = bfs(a); 54 cout << sum << endl; 55 } 56 return 0; 57 }