queue队列练习:信息学奥赛:1360:奇怪的电梯(lift)

信息学奥赛:1360:奇怪的电梯(lift)

题目链接
思路:
还是bfs,但bfs用到了队列。
建一个一维数组s,下标表示楼层,值表示当前楼层上的那个数。

一开始没有对走过的层数做标记,会一直死循环导致内存超限。
后来,做了标记,但做的不对,用的是走过的楼层i,把s[i]置为-1;
改正了标记的错误,在最后还是用新建一个一位数组bol来标记。

#include<iostream>
#include<queue>
using namespace std;
const int N = 205;
int s[N];
bool bol[N] = {false};   // VS在这里会全部初始化false,我也这样默认的,结果oj通过了
int n, A, B;

struct Point {
	int x, step;
};

int bfs(int start) {
	bol[start] = true;   // 走过的楼层标记
	queue<Point>q;	
	Point now, next;
	now.x = start;
	now.step = 0;
	q.push(now);
	while (!q.empty()) {
		now = q.front();
		if (now.x == B)
			return now.step;
		// 判断能否上
		next.x = now.x + s[now.x];     // 这之前我没有把s[now.x]置为-1,因为这里要用到
		if (0 < next.x && next.x <= n && !bol[next.x]) {
			bol[next.x] = true;
			next.step = now.step + 1;
			q.push(next);
		}
		// 判断是否能下
		next.x = now.x - s[now.x];
		if (0 < next.x && next.x <= n && !bol[next.x]) {
			bol[next.x] = true;
			next.step = now.step + 1;
			q.push(next);
		}
		q.pop();
	}
	return -1;
}

int main() {
	cin >> n >> A >> B;
	for (int i = 1; i <= n; i++)
		cin >> s[i];

	cout << bfs(A);
	//getchar();
	//getchar();
	return 0;
}

和同学讨论的时候很简单,动手的时候尽然花了几个小时。

猜你喜欢

转载自blog.csdn.net/qq_43833364/article/details/105666175