94求助
查看原帖
94求助
780505
x1489631649楼主2023/11/25 23:21
#include <bits/stdc++.h>
using namespace std;
int a[100000],vis[100000],flag,n,A,B;
struct node{
	int x;
	int step;
}q[10000];
void bfs()
{
	int t,h;
	t=h=1;
	q[h].x=A;
	q[h].step=0;
	vis[h]=1;
	while(h<=t)
	{
		int nx1=q[h].x+a[q[h].x];
		int nx2=q[h].x-a[q[h].x];
		if(nx1==B||nx2==B)
		{
			cout<<q[h].step+1;
			flag=1;
			return;
		}
		if(nx1<=n&&nx1>0&&vis[nx1]==0)
		{
			t++;
			q[t].x=nx1;
			q[t].step=q[h].step+1;
			vis[nx1]=1;
		}
		if(nx2<=n&&nx2>0&&vis[nx2]==0)
		{
			t++;
			q[t].x=nx2;
			q[t].step=q[h].step+1;
			vis[nx2]=1;
		}
		h++;
	}
}
int main()
{
	cin>>n>>A>>B;
	for(int i=1;i<=n;i++)
		cin>>a[i];
	bfs();
	if(flag==0)
		cout<<-1;
	return 0;
}
2023/11/25 23:21
加载中...