洛谷P1135 奇怪的电梯 - BFS宽度优先搜索

/*
https://www.luogu.org/problemnew/show/P1135
洛谷 - 奇怪的电梯
本题有很多方法,但是我还是用了BFS(毕竟简单)。。。 
但是写起来发现有很多细节需要注意的。。。

1.	第一个错误在楼层的计数:
	每一个节点向上向下走都是有各自不同的步数的, 
	本题中每一个节点可能会有两个子节点,也可能并没有, 
	所以不能用一个全局变量直接储存步数。 

2.	开始的初始判断:
	如果 A == B 直接输出0 

3.	判重:
	本题是一维搜索,不像二维不需要判重。 
*/

#include <bits/stdc++.h>
using namespace std;

int k[201];
int li[400001][2];	//li[][0] is 楼数, and li[][1] is 到本楼的步数 
int book[201];
int head = 0;		//li[head] is the first one...
int tail = 1;		//tail pointed the next one...(li[tail-1] is the last one)
int N, A, B;		//from A to B	(Top is N and floot is 1)
bool isFound = false;

int main()
{
	//freopen("testdata.in", "r", stdin);
	//freopen("out.txt", "w", stdout);
	int t;
	cin >> N >> A >> B;
	for (int i=1; i<=N; i++)
		cin >> k[i];
	
	if (A == B)
	{
		cout << 0 << endl;
		return 0;
	}
	
	li[head][0] = A;
	li[head][1] = 0;
	tail++;
	
	while (head < tail)		//until the list is empty
	{
		if (li[head][0] == B)
		{
			isFound = true;
			break;
		}
		//cout << "step " << li[head][1] << " : " << li[head][0] << endl;
		t = li[head][0] + k[li[head][0]];
		if (t <= N && book[li[head][0]] == 0)
		//if (t <= N)
		{
			li[tail - 1][0] = t;
			li[tail - 1][1] = li[head][1] + 1;
			tail++;
		}
		t = li[head][0] - k[li[head][0]];
		if (t > 0 && book[li[head][0]] == 0)
		//if (t > 0)
		{
			li[tail - 1][0] = t;
			li[tail - 1][1] = li[head][1] + 1;
			tail++;
		}
		book[li[head][0]] = 1;
		head++;
		//li[head][1] = li[head-1][1] + 1;
	}
	cout << (isFound ? li[head][1] : -1) << endl;
	return 0;
}
posted @ 2018-03-03 20:47  TonyLiang2018  阅读(316)  评论(0)    收藏  举报