poj 3278 Catch That Cow

简介:
Catch That Cow
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 62146   Accepted: 19460

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


题目大意:就是给你两个数 n 和 k 让你通过以下三种方法使得 n -> k;

1) n + 1;

2) n - 1;

3)n * 2;

看怎么样通过上述三种方法使得 n 变成 k 而且需要的步骤最少;


样例解释:

5 17

5 -> 10(1) -> 9(2) -> 18(3) -> 17(4)

所以只需要 4 步


解题思路:这是广搜的类型,所以需要bfs就行了,具体注意的问题会在代码里给出:


/*
Date : 2015-09-08 晚上

Author : ITAK

Motto :

今日的我要超越昨日的我,明日的我要胜过今日的我;
以创作出更好的代码为目标,不断地超越自己。
*/
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;

const int maxn = 100001;

bool vis[maxn];
int n,k;
int fac[maxn];///记录结果
int dis[maxn];//

void bfs()
{
    int front, rear, dx, dy;
    rear = front = 0;
    dis[0] = n, fac[n] = 0;
    vis[n] = 1;
    while(front <= rear)
    {
        dx = dis[front];
        
        dy = dx - 1;
        if(dy>=0 && !vis[dy])///剪枝 -> dy>=0
        {
            rear++;
            dis[rear] = dy;
            fac[dy] = fac[dx] + 1;
            vis[dy] = 1;
        }
        dy = dx + 1;
        if(dy<maxn && !vis[dy])///剪枝 -> dy < maxn
        {
            rear++;
            dis[rear] = dy;
            fac[dy] = fac[dx] + 1;
            vis[dy] = 1;
        }
        dy = dx*2;
        if(dy<maxn && !vis[dy])///剪枝 -> dy < maxn
        {
            rear++;
            dis[rear] = dy;
            fac[dy] = fac[dx] + 1;
            vis[dy]  = 1;
        }
        if(vis[k])///结束
            break;
        front++;
    }
}
int main()
{
    while(~scanf("%d%d",&n,&k))
    {
        memset(vis, 0, sizeof(vis));
        bfs();
        cout<<fac[k]<<endl;
    }
    return 0;
}


目录
相关文章
|
Java API
从JDK源码看System.exit
前言 在编写的Java程序中有时会遇到用 System.exit 来关闭JVM,其中调用 exit 方法时会包含一个状态参数n,即System.exit(n)。
1303 0
B-POJ-3278 Catch That Cow
Description Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately.
1291 0