石油大oj 1825奇怪的电梯 bfs

链接:http://exam.upc.edu.cn/problem.php?id=1825

题目描述

呵呵,有一天我做了一个梦,梦见了一种很奇怪的电梯。大楼的每一层楼都可以停电梯,而且第i层楼(1<=i<=N)上有一个数字Ki(0<=Ki<=N)。电梯只有四个按钮:开,关,上,下。上下的层数等于当前楼层上的那个数字。当然,如果不能满足要求,相应的按钮就会失灵。例如:3 3 1 2 5代表了Ki(K1=3,K2=3,……),从一楼开始。在一楼,按“上”可以到4楼,按“下”是不起作用的,因为没有-2楼。那么,从A楼到B楼至少要按几次按钮呢?

输入

输入共有二行,第一行为三个用空格隔开的正整数,表示N,A,B(1≤N≤200, 1≤A,B≤N),第二行为N个用空格隔开的正整数,表示Ki。

输出

输出仅一行,即最少按键次数,若无法到达,则输出-1。

样例输入

5 1 5
3 3 1 2 5

样例输出

3

思路:求最短路问题,用bfs广度优先搜索

比赛做了很久,因为搜索没有学好用dfs做了。。。

bfs:宽度优先搜索算法(又称广度优先搜索)是最简便的图的搜索算法之一,这一算法也是很多重要的图的算法的原型。Dijkstra单源最短路径算法和Prim最小生成树算法都采用了和宽度优先搜索类似的思想。其别名又叫BFS,属于一种盲目搜寻法,目的是系统地展开并检查图中的所有节点,以找寻结果。换句话说,它并不考虑结果的可能位置,彻底地搜索整张图,直到找到结果为止。(来自百度百科)

代码:(柴学长的)

#include <set>
#include <map>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <cctype>
#include <cstdio>
#include <string>
#include <vector>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <iostream>
#include <algorithm>
#define pi acos(-1.0)
#define maxn (101000 + 50)
#define mol 1000000009
#define inf 0x3f3f3f3f
#define Lowbit(x) (x & (-x))
using namespace std;
typedef long long int LLI;


int a[maxn], n;
bool flag[maxn];

struct node {
	int x;
	int t; //t储存移动次数
} re[maxn];


int BFS(int st, int et) {
	queue<node> Que;
	fill(flag, flag + maxn, 0);//初始化
	node temp;
	temp.x = st, temp.t = 0;
	Que.push(temp); //把起点加入队列
	flag[st] = 1; //标记
	while (!Que.empty()) {
		node ppp = Que.front();
		Que.pop();
		if (ppp.x == et)return ppp.t;
		int x = ppp.x;
		if (x - a[x] >= 1 && !flag[x - a[x]]) {//满足可以向下的条件
			flag[x - a[x]] = 1;
			temp.x = x - a[x];
			temp.t = ppp.t + 1;
			Que.push(temp);
		}
		if (x + a[x] <= n && !flag[x + a[x]]) {//满足可以向下的条件
			flag[x + a[x]] = 1;
			temp.x = x + a[x];
			temp.t = ppp.t + 1;
			Que.push(temp);
		}
	}
	return -1;
}


int main() {
	int p, q;
	scanf("%d%d%d", &n, &p, &q);
	for (int i = 1; i <= n; i++)
		scanf("%d", &a[i]);
	printf("%d\n", BFS(p, q));
	return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值