50分求助
查看原帖
50分求助
571348
PartiallyCorrect楼主2023/7/11 15:45
#include<bits/stdc++.h>
using namespace std;
const int N = 205;
int a[N],n;
queue<int> q;
bool check(int x)
{
	return x < 0 or x > n?false:true;
}
int main()
{
	int A, B;
	cin >> n >> A >> B;
	for(int i = 1 ; i <= n ; i++)
		cin >> a[i] ;
	q.push(A);
	int cnt = 0, f = 2e9;
	while(!q.empty())
	{
		int t = q.front();
		q.pop();
		if(t == B)
		{
			f = min(f, cnt);
			continue;
		}
		if(cnt > n)
		{
			cout << -1 ;
			return 0;
		}
		if(check(t + a[t]))q.push(t + a[t]),cnt++;
		if(check(t - a[t]))q.push(t - a[t]),cnt++;
	}
	if(f > n)cout << -1;
	else cout << f ;
	return 0;
}
2023/7/11 15:45
加载中...