题意:一个人要从某一层电梯到另一层电梯 ,每层电梯都只能上或者下特定层数,问你从某一层到另一层最少需要按多少次电梯按钮
如果你看了数据范围的话你就会想到用BFS广搜
用广搜就会想到队列
我先说说队列的几个基本语句吧
include<queque>
queque<这个里面可以是很多类型也可以是结构体>q
入队q.push(x)将x接到对位
q.pop(x)弹出队列的第一个元素
q.front(x)访问数组的第一个元素
q.back(x)访问数组的最后一个元素
判断队列空,如例:q.empty(),当队列空时,返回true。
访问队列中的元素个数,如例:q.size()
这道题需要查重就是看这个点是否被找过了 下面看代码 在代码中还有说明
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<iostream>
#include<queue>
using namespace std;
int s,e,n;
int ss[205],vis[205];
struct node
{
int x,step;
};
int check(int x) //判断是否越界的函数
{
if(x<=0||x > n)
return 1;
return 0;
}
int BFS()
{
queue<node> Q;
node a,next;
int i;
a.x = s;
a.step = 0;
vis[a.x] = 1;
Q.push(a);
while(!Q.empty())
{
a = Q.front();
Q.pop();
if(a.x == e)
return a.step;
for(i = -1; i <= 1; i+=2)
{
next = a;
next.x += i * ss[next.x];
if(check(next.x)||vis[next.x]) //先看看是否越界 然后看看是否找过了
{
continue;
}
vis[next.x] = 1;
next.step++;
Q.push(next);
}
}
return -1;
}
int main()
{
int i;
while(~scanf("%d",&n)&&n)
{
scanf("%d%d",&s,&e);
memset(vis,0,sizeof(vis));
for(i = 1; i <= n; i++)
{
scanf("%d",&ss[i]);
}
printf("%d\n",BFS());
}
return 0;
}