您的位置:首页 > 其它

(BFS)A strange lift--HDOJ

2017-08-08 15:36 453 查看
A strange lift

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

Total Submission(s): 1068 Accepted Submission(s): 502

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 is on floor A,and you want to go to floor B,how many times at least he havt 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

总结:

题意理解错了,当成了双向边,很无奈。

这道题可以构造成一个有向图,用BFS对图进行搜索,第一次遇到终点就是最短路

#include<iostream>
#include<string.h>
#include<string>
#include<stdio.h>
#include<algorithm>
#include<queue>
#include<math.h>
#define PI acos(-1.0)
#define eps 0.00000001

using namespace std;
typedef struct Node
{
int v,cnt;
}Node;

int vis[201],ans=999999,n,st,ed;
int BFS(int x,vector<int >vec[])
{
queue<Node > q;
Node t;
t.v = x,t.cnt = 0;
q.push(t);

while(!q.empty())
{
Node tmp = q.front();
q.pop();
vector<int >::iterator iter = vec[tmp.v].begin();
while(iter != vec[tmp.v].end())
{
if(*iter == ed) return (tmp.cnt+1);
if(!vis[*iter])
{
vis[*iter] = 1;
Node nxt;
nxt.v = *iter;
nxt.cnt = tmp.cnt + 1;
q.push(nxt);
}
iter++;
}
}
return -1;
}
int main(void)
{
//   freopen("in.txt","r",stdin);

while(scanf("%d",&n) && n)
{
vector<int > vec[201];
memset(vis,0,sizeof(vis));
scanf("%d %d",&st,&ed);

for(int i=1; i<=n; ++i)
{
int a,b,t;
scanf("%d",&t);
a = i - t;
b = t + i;
if(a>=1 && a<=n)
{
vec[i].push_back(a);
//     vec[a].push_back(i);
}

if(b>=1 && b<=n)
{
vec[i].push_back(b);
//          vec[b].push_back(i);
}
}
if(st == ed)
{
cout << '0'<<endl;
continue;
}
vis[st] = 1;
ans = BFS(st,vec);
cout << ans <<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  bfs