A strange lift
Problem Description
Here comes the problem: when you are on floor A,and you want to go to floor B,how many times at least he has to press the button "UP" or "DOWN"?
The first line contains three integers N ,A,B( 1 <= N,A,B <= 200) which describe above,The second line consist N integers k1,k2,....kn.
A single 0 indicate the end of the input.
#include<queue>
#include<string.h>
#include<iostream>
using namespace std;
const int num = 255;
int floor[num][2];//表示上下楼
bool vis[num];//标识楼层是否到达过
//定义楼层
struct node{
int pos;//楼层
int cen;//积累到达该层移动的次数
};
node temp;
queue<node> q;
int N,A,B;
int BFS(){
memset(vis,false,sizeof(vis));
while(!q.empty()){
temp = q.front();
q.pop();
vis[temp.pos] = true;
if(temp.pos == B){
return temp.cen;
}
int up = floor[temp.pos][0];
int down = floor[temp.pos][1];
node temp2;
if(up != -1 && !vis[up]){
temp2.pos = up;
temp2.cen = temp.cen + 1;
q.push(temp2);
}
if(down != -1 && !vis[down]){
temp2.pos = down;
temp2.cen = temp.cen + 1;
q.push(temp2);
}
}
return -1;
}
int main(){
while(cin >> N && N){
cin >> A >> B;
memset(floor,-1,sizeof(floor));
//清空队列
while(!q.empty())
q.pop();
for(int i = 1;i <= N;i ++){
int t = 0;
cin >> t;
temp.pos = i;
if(i + t <= N){
//上升后到达的层数
floor[i][0] = t + i;
}
if(i - t >= 1){
//下降后到达的层数
floor[i][1] = i - t;
}
if(i == A){
temp.cen = 0;
q.push(temp);
}
}
int num = BFS();
cout << num << endl;
}
return 0;
}

浙公网安备 33010602011771号