洛谷 P1135 奇怪的电梯
P1135 奇怪的电梯
spfa
1 #include<bits/stdc++.h> 2 using namespace std; 3 #define maxn 1000000 4 #define inf 1<<30 5 int n,m,x,y,z,num,head[maxn],dis[maxn],a,b; 6 struct Edge{ 7 int u,v,d,next; 8 }edge[maxn]; 9 char ch; 10 inline void read(int &now) 11 { 12 ch=getchar(); now=0; 13 while(ch>'9'||ch<'0') ch=getchar(); 14 while(ch>='0'&&ch<='9') now=now*10+ch-'0',ch=getchar(); 15 } 16 void add_Edge(int u,int v,int d) 17 { 18 edge[++num].v=v; 19 edge[num].d=d; 20 edge[num].next=head[u]; 21 head[u]=num; 22 } 23 void spfa(int now) 24 { 25 queue<int>que; 26 bool vis[maxn]; 27 for(int i=1;i<=n;i++) dis[i]=inf,vis[i]=false; 28 dis[now]=0,vis[now]=true; 29 que.push(now); 30 while(!que.empty()) 31 { 32 int cur=que.front(); que.pop(); 33 for(int i=head[cur];i;i=edge[i].next) 34 { 35 if(dis[edge[i].v]>dis[cur]+edge[i].d) 36 { 37 dis[edge[i].v]=dis[cur]+edge[i].d; 38 if(!vis[edge[i].v]) 39 { 40 vis[edge[i].v]=true; 41 que.push(edge[i].v); 42 } 43 } 44 } 45 vis[cur]=false; 46 } 47 } 48 int main() 49 { 50 read(n); read(a); read(b); 51 for(int i=1;i<=n;i++) 52 { 53 read(x); if(i-x>0) add_Edge(i,i-x,1); 54 if(i+x<=n) add_Edge(i,i+x,1); 55 } 56 spfa(a); 57 if(dis[b]==inf) printf("-1\n"); 58 else printf("%d\n",dis[b]); 59 return 0; 60 }