1 条题解
-
0938936 LV 7 MOD @ 2019-09-21 19:56:19
使用bfs(广度优先搜索)解题即可
复杂度O(n)#include<iostream> #include<cstring> #include<algorithm> using namespace std; int n,s,t,a[201],cmp[201],val[201]; int main(){ cin>>n>>s>>t; int i; for(i=1;i<=n;i++){ cin>>a[i]; cmp[i]=0; val[i]=-1; } if(s==t) { cout<<0;return 0; } int l,r,v,qu[1001]; l=r=1; qu[1]=s; val[s]=0; cmp[s]=1;//cmp标记已走过楼层,因为正确路线不能重复 while(l<=r && r<=1000){ v=qu[l++]; if(v+a[v]<=n) if(cmp[v+a[v]]==0){ qu[++r]=v+a[v]; val[v+a[v]]=val[v]+1; cmp[v+a[v]]=1; } if(v-a[v]>=1) if(cmp[v-a[v]]==0){ qu[++r]=v-a[v]; val[v-a[v]]=val[v]+1; cmp[v-a[v]]=1; } } cout<<val[t]; return 0; }
- 1