HDU 2717 Catch That Cow(bfs)

题目代号:HDU 2717

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2717

Catch That Cow

Time Limit: 5000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 15682    Accepted Submission(s): 4700


Problem 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.
 

 

题目大意:有x坐标轴,农夫在n,牛在k。农夫每次可以移动到n-1, n+1, n*2的点。求最少到达k的步数。

解题思路:直接bfs怎样都不会超时。

AC代码:

# include <stdio.h>
# include <string.h>
# include <stdlib.h>
# include <iostream>
# include <fstream>
# include <vector>
# include <queue>
# include <stack>
# include <map>
# include <math.h>
# include <algorithm>
using namespace std;
# define pi acos(-1.0)
# define mem(a,b) memset(a,b,sizeof(a))
# define FOR(i,a,n) for(int i=a; i<=n; ++i)
# define For(i,n,a) for(int i=n; i>=a; --i)
# define FO(i,a,n) for(int i=a; i<n; ++i)
# define Fo(i,n,a) for(int i=n; i>a ;--i)
typedef long long LL;
typedef unsigned long long ULL;

int n,k;
int a[200005];
struct node
{
    int x,step;
};

queue<node>Q;

int bfs()
{
    while(!Q.empty())
    {
        int x=Q.front().x;
        int step=Q.front().step;
        Q.pop();
        if(x==k)
        {
            return step;
        }
        for(int i=1;i<=3;i++)
        {
            int tx=x;
            if(i==1)tx+=1;
            else if(i==2)tx-=1;
            else tx*=2;
            if(tx>=0&&tx<=200000&&a[tx]==0)
            {
                Q.push(node{tx,step+1});
                a[tx]=1;
            }
        }
    }
    return -1;
}

int main()
{
    //freopen("in.txt", "r", stdin);
    while(~scanf("%d%d",&n,&k))
    {
        while(!Q.empty())Q.pop();
        mem(a,0);
        Q.push(node{n,0});
        a[n]=1;
        cout<<bfs()<<endl;
    }
    return 0;
}

 

posted @ 2017-07-27 21:57  韵祈  阅读(139)  评论(0编辑  收藏  举报