http://acm.hdu.edu.cn/showproblem.php?pid=2717,有所借鉴哦!!

题目意思就是:要求在一个队列中(在一条直线上),一个人在队列中的位置(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;
      }
   }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值