【题目链接】
http://acm.hdu.edu.cn/showproblem.php?pid=1548
【解题报告】
从A出发,问到B的最短路径。
其实就是一个最短路问题。使用优先队列维护一下就好。不熟悉的人可能会用深搜去求解,不过暂时没想明白深搜会错到哪里,留个坑以后补。
暂时远离ACM圈,以后随心情做点题,一切事情随缘吧。
【参考代码】
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn=1e3;
int N,A,B;
int K[maxn],vis[maxn];
struct Node{
int ranks,pos;
bool operator < ( const Node& rhs )const{
return ranks>rhs.ranks;
}
};
priority_queue<Node>q;
void update( int p, int rhs )
{
if(!vis[p])
{
Node now; now.pos=p; now.ranks=rhs+1;
q.push( now );
vis[p]=1;
}
}
int solve()
{
while( !q.empty() )q.pop();
vis[A]=1;
Node start; start.pos=A; start.ranks=0;
q.push(start);
while(!q.empty())
{
Node now=q.top(); q.pop();
if( now.pos==B ) return now.ranks;
int down=now.pos-K[ now.pos ];
int up=now.pos+K[now.pos];
if( down>0 ) update( down,now.ranks );
if( up<=N ) update( up,now.ranks );
}
return -1;
}
int main()
{
while( ~scanf( "%d",&N ) && N )
{
scanf( "%d%d",&A,&B );
memset( vis,0,sizeof vis );
for( int i=1;i<=N;i++ ) scanf( "%d",K+i );
printf( "%d\n",solve() );
}
return 0;
}