MLE求优化指点
查看原帖
MLE求优化指点
381392
Radno楼主2021/7/16 11:12

BFS算法MLE求大佬指点优化

代码如下:

#include<queue>
#include<iostream>
using namespace std;
int n,s,e;
int k[205];
int dir[2] = { 1,-1 };
struct Q
{
	int f,step;
};	
void bfs() {
	queue<Q> q;
	Q N;
	N.f = s;
	N.step = 0;
	q.push(N);
	while (!q.empty()) {
		N = q.front();
		q.pop();
		if (N.f == e) {
			cout << N.step;
			goto here;
		}
		for (int i = 0; i < 2; i++)
		{
			int floor = k[N.f]*dir[i]+N.f;
			if (floor > n ||floor <= 0) {
				continue;
			}
			N.f = floor;
			N.step = N.step + 1;
			q.push(N);
		}
	}
	cout << "-1";
	here:
	return;
}

int main() {
	cin >> n >> s >> e;
	for (int i = 1; i <= n; i++) {
		cin >> k[i];
	}
	bfs();
	return 0;
}
2021/7/16 11:12
加载中...