POJ-3278 Catch That Cow(bfs)

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

思路:

向X-1、X+1和2*X进行bfs,开一个整型的dp数组,既进行了是否已经到达过的标记,又统计了步数。

上AC代码:

#include <stdio.h>
#include <queue>
#include <string.h>
using namespace std;
int n,k;
int dp[100001];
int main()
{
    while(~scanf("%d%d",&n,&k))
    {
        memset(dp,-1,sizeof(dp));
        queue<int> que;
        que.push(n);
        dp[n]=0;
        while(!que.empty())
        {
            int now=que.front();
            if(now==k)
            {
                break;
            }
            que.pop();
            if(now-1>=0&&dp[now-1]==-1)
            {
                dp[now-1]=dp[now]+1;
                que.push(now-1);
            }
            if(now+1<=100000&&dp[now+1]==-1)
            {
                dp[now+1]=dp[now]+1;
                que.push(now+1);
            }
            if(2*now<=100000&&dp[2*now]==-1)
            {
                dp[2*now]=dp[now]+1;
                que.push(2*now);
            }
        }
        printf("%d\n",dp[k]);
    }
    return 0;
}
发布了72 篇原创文章 · 获赞 203 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/weixin_41676881/article/details/88934609
今日推荐