POJ 3278 Catch That Cow

来源:互联网 发布:php用apache还是nginx 编辑:程序博客网 时间:2024/06/07 06:56
Catch That Cow
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 51447 Accepted: 16134

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 - 1 or + 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.


题意:

     给出起始位置n,有三种操作x+1,x-1,2*x,求最少的操作次数,使x==k。


题解:

     广搜,裸的广搜会MLE,要加剪枝,还要用数组标记。一直MLE,就调整为每次出现一个新位置就判断是否结束,导致后来忘记考虑n==k的情况%>_<%

    剪枝1.x>k,2*x不用走,只会越走越远。

    剪枝2.x>k,x+1不用走,使x变小的只有x-1,x+1再x-1只会增加步数。

    剪枝3.x-1>=0,x为负数时,只会增加步数或越走越远。


代码:

#include <iostream>#include <cstdio>#include <cstring>#include <queue>#include <algorithm>using namespace std;int n,k;int ans;const int maxn=200000+100;struct node{    int x;    int cur;} p;bool vis[maxn];queue<node> q;void BFS(){    node p;    p.x=n;    p.cur=0;    vis[n]=true;    while(!q.empty())        q.pop();    q.push(p);    while(!q.empty())    {        node now;        node tmp=q.front();        q.pop();        if(tmp.x==k)//n==k时        {            ans=tmp.cur;            return;        }        if(tmp.x<k&&!vis[tmp.x*2])//剪枝        {            now.x=tmp.x*2;            now.cur=tmp.cur+1;            vis[now.x]=true;            if(now.x==k)            {                ans=now.cur;                return;            }            q.push(now);        }        if(tmp.x<k&&!vis[tmp.x+1])//剪枝        {            now.x=tmp.x+1;            now.cur=tmp.cur+1;            vis[now.x]=true;            if(now.x==k)            {                ans=now.cur;                return;            }            q.push(now);        }        if(tmp.x-1>=0&&!vis[tmp.x-1])//剪枝        {            now.x=tmp.x-1;            now.cur=tmp.cur+1;            vis[now.x]=true;            if(now.x==k)            {                ans=now.cur;                return;            }            q.push(now);        }    }}int main(){    while(~scanf("%d%d",&n,&k))    {        memset(vis,false,sizeof(vis));        BFS();        printf("%d\n",ans);    }    return 0;}


0 0