Description
Input
Output
Sample Input
5 1 5 3 3 1 2 5 0
Sample Output
3
#include <stdio.h>
#include <queue>
#include <string.h>
using namespace std;
int st,ed,n;
int a[205];
bool vis[205];
struct node
{
int pos;
int cost;
friend bool operator<(node x,node y)
{
return x.cost>y.cost;
}
};
int bfs()
{
priority_queue<node>s;
while(!s.empty()) s.pop();
node temp,temp1;
temp.pos=st,temp.cost=0;
s.push(temp);
while(!s.empty())
{
temp=temp1=s.top();s.pop();
if(temp.pos==ed) return temp.cost;
if(vis[temp.pos]) continue;
vis[temp.pos]=true;
temp.pos+=a[temp.pos];
temp.cost++;
if(temp.pos<=n)
s.push(temp);
temp=temp1;
temp.pos-=a[temp.pos];
temp.cost++;
if(temp.pos>=1)
s.push(temp);
}
return -1;
}
int main()
{
while(~scanf("%d",&n)&&n)
{
memset(vis,0,sizeof(vis));
scanf("%d %d",&st,&ed);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("%d\n",bfs());
}
return 0;
}
原文:http://blog.csdn.net/su20145104009/article/details/51539351