hdoj-2717-Catch That Cow

来源:互联网 发布:淘宝售后客服热线 编辑:程序博客网 时间:2024/06/06 09:13

Description
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.

  • Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
  • Teleporting: FJ can move from any point X to the point 2 × X in a single minute.

If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?

Input
Line 1: Two space-separated integers: N and K

Output
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.

Sample Input

5 17

Sample Output

4

Hint

The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.

一个人在追一个宠物,有两种方式,步行:每秒前进或后退1步,借助传输工具:每秒前进2*x步;
直接bfs就好了

#include<cstdio>#include<queue>#include<cstring>#include<iostream>#include<algorithm>using namespace std;int vis[100005];int x,ex,n,k;struct go{    int x,step;};int bfs(){    queue<go>q;    while(!q.empty()) q.pop();    go next,now;    now.step=0;    now.x=n;    vis[n]=1;    q.push(now);    while(!q.empty())    {        now=q.front();        q.pop();        for(int i=1;i<=3;i++)        {            if(i==1) next.x=now.x-1;            else if(i==2) next.x=now.x+1;            else if(i==3) next.x=now.x*2;            next.step=now.step+1;            if(next.x==k)              return next.step;              if(next.x>=0&&next.x<=100000&&!vis[next.x])              {                  q.push(next);                  vis[next.x]=1;              }        }    }}int main(){    while(scanf("%d%d",&n,&k)!=EOF)    {        memset(vis,0,sizeof(vis));        x=n;        ex=k;        if(x>=ex)        {            printf("%d\n",x-ex);            continue;        }        int ans=bfs();        printf("%d\n",ans);    }    return 0;}
0 0