题目意思就是:要求在一个队列中(在一条直线上),一个人在队列中的位置(X),而一头牛的位置在(Y),要求人要在最短时间内找到牛?
方法有两个:1:人可以单位时间前进一步或后退一步;2;人可以坐飞机,每单位时间内可以到达(2*X)的位置。
思路:可以深搜,从初始位置找,并赋初始位置map[start]=1;即开始搜索,,,分别从方法入手(即人找到牛的方法),分别写出各自的表达式(尤其注意前后位置的改变)。。以下为AC的代码。。
#include<iostream>
#include<cstdio>#include<cmath>
#include<queue>
#include<cstdlib>
#include<cstring>
using namespace std;
# define max 100009
int map[max];
int star,end;
void bfs();
int main()
{
while(scanf("%d%d",&star,&end)!=EOF)
{
// if(s==e)
// printf("0\n");
if(star>=end)
map[end]=star-end+1;
else
bfs();
printf("%d\n",map[end]-1);
}
return 0;
}
void bfs()
{
int i,j;
int last,next;
queue<int>Q;
Q.push(star);
memset(map,0,sizeof(map));
map[star]=1;
while(!Q.empty())
{
last=Q.front();
Q.pop();
if(star==end)
break;
next=last-1;
if(next>=0&&!map[next])
{
Q.push(next);
map[next]=map[last]+1;
}
next=last+1;
if(!map[next])
{
Q.push(next);
map[next]=map[last]+1;
}
next=last*2;
if(next<=100000 && next-end<end-last && !map[next])
{
Q.push(next);
map[next]=map[last]+1;
}
}
}