题目传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1548
题目大意:每一层的电梯只有两个按钮,向上或者向下,且向上向下的层数是规定好的,在输入中读取的.要你判断最少多少次可以从A楼到B楼.
简单的bfs即可.
AC代码:
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
#define Size 201
struct Node
{
int floor;
int step;
bool operator < (Node a) const
{
//次数优先.
return this->step > a.step;
}
};
int N, A, B;
int world[Size];
int visit[Size][2];
bool judge(Node a)
{
if (a.floor >= 1 && a.floor <= N)
return true;
return false;
}
int bfs()
{
priority_queue<Node> temp;
Node now, next, s;
s.floor = A;
s.step = 0;
temp.push(s);
while (!temp.empty())
{
now = temp.top();
temp.pop();
//判断是否到目的地.
if (now.floor == B)
return now.step;
//枚举两个操作.
for (int i = 0; i < 2; ++i)
{
if (i == 0)
next.floor = now.floor + world[now.floor];
else if (i == 1)
next.floor = now.floor - world[now.floor];
//判断是否可行.
if (judge(next) && visit[now.floor][i] == 0)
{
next.step = now.step + 1;
//增加访问权限.
visit[now.floor][i] = 1;
temp.push(next);
}
}
}
return -1;
}
int main()
{
while (1)
{
scanf("%d%d%d", &N, &A,&B);
if (N == 0)
break;
memset(world,0,sizeof(world));
memset(visit,0,sizeof(visit));
for (int i = 1; i <= N; ++i)
{
scanf("%d", &world[i]);
}
printf("%d\n", bfs());
}
return 0;
}