您的位置:首页 > 其它

#HDU 1548 A strange lift 【BFS】

2016-02-23 00:26 387 查看

题目:


A strange lift

[b]Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 17969    Accepted Submission(s): 6707
[/b]

Problem Description

There is a strange lift.The lift can stop can at every floor as you want, and there is a number Ki(0 <= Ki <= N) on every floor.The lift have just two buttons: up and down.When you at floor i,if you press the button "UP" , you will go up Ki floor,i.e,you will
go to the i+Ki th floor,as the same, if you press the button "DOWN" , you will go down Ki floor,i.e,you will go to the i-Ki th floor. Of course, the lift can't go up high than N,and can't go down lower than 1. For example, there is a buliding with 5 floors,
and k1 = 3, k2 = 3,k3 = 1,k4 = 2, k5 = 5.Begining from the 1 st floor,you can press the button "UP", and you'll go up to the 4 th floor,and if you press the button "DOWN", the lift can't do it, because it can't go down to the -2 th floor,as you know ,the -2
th floor isn't exist.

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"?

 

Input

The input consists of several test cases.,Each test case contains two lines.

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.

 

Output

For each case of the input output a interger, the least times you have to press the button when you on floor A,and you want to go to floor B.If you can't reach floor B,printf "-1".

 

Sample Input

5 1 5
3 3 1 2 5
0

 

Sample Output

3

 

Recommend

8600

给定一个K层的楼,一个电梯,每层带有一个数据S,从该层出发只能上升或下降S层,求是否能到达某个指定楼层。

思路:以初始楼层为起点开始BFS搜索,搜索完成后,若vis[目标楼层]已被标记,则输出最短次数。否则输出-1。

题目较简单,

#include<iostream>
#include<algorithm>
#include<queue>
#include<string.h>
#include<math.h>
#include<vector>

using namespace std;

long long ans, n, be, ed;
int data[205][2];
queue<int>que;

int main()
{
while (cin >> n)
{
memset(data, 0, sizeof(data));
ans = 0;
if (n == 0)
{
return 0;
}
cin >> be >> ed;
for (size_t i = 1; i <= n; i++)
{
cin >> data[i][0];
}
que.push(be);
while (!que.empty())
{
int temp = que.front();
if (temp - data[temp][0]>0 && (data[temp - data[temp][0]][1] == 0 || data[temp - data[temp][0]][1] >data[temp][1] + 1))
{
data[temp - data[temp][0]][1] = data[temp][1] + 1;
que.push(temp - data[temp][0]);
}
if (temp + data[temp][0] <= n && (data[temp + data[temp][0]][1] == 0 || data[temp + data[temp][0]][1] >data[temp][1] + 1))
{
data[temp + data[temp][0]][1] = data[temp][1] + 1;
que.push(temp + data[temp][0]);
}
que.pop();
}
if (data[ed][1] == 0)
{
cout << "-1\n";
}
else
{
if (be == ed)
{
cout << "0\n";
}
else
{
cout << data[ed][1] << "\n";
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  连通图 算法 bfs dfs ACM