首页 > 代码库 > http://poj.org/problem?id=3278(bfs)

http://poj.org/problem?id=3278(bfs)

Catch That Cow
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 76935 Accepted: 24323

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.
 
题意:给出两个数star,end,给出x-1,x+1,x*2四种运算,使star变成end;
 
思路:直接bfs就好了;
 
代码:
#include <iostream>
#include <string.h>
#include <queue>
#define MAXN 200000+10
using namespace std;

struct Node       //***用结构体表示节点,x表示当前值,step记录当前步数
{
    int x, step;
};

int star, end, vis[MAXN];

int bfs(int x)
{
    Node a, b, c;
    a.x = x, a.step = 0;      //***赋初值
    queue<Node>q;            //***用队列实现
    q.push(a);                //***头节点入队
    while(!q.empty())         //***如果队列不为空,继续循环
    {
        b = q.front();        //***取当前队列的头节点做父节点并将其从队列中删除
        q.pop();
        vis[b.x] = 1;       //***标记
        if(b.x == end)       //***如果达到目标,返回步数
        {
            return b.step;
        }
        c = b;                  //***符合条件的儿子入队
        if(c.x >= 1 && !vis[c.x-1])
        {
            c.x-=1;
            c.step++;
            vis[c.x]=1;
            q.push(c);
        }
        c = b;
        if(c.x < end && !vis[c.x+1])
        {
            c.x+=1;
            c.step++;
            vis[c.x]=1;
            q.push(c);
        }
        c = b;
        if(c.x < end && !vis[2*c.x])
        {
            c.x*=2;
            c.step++;
            vis[c.x]=1;
            q.push(c);
        }
    }
    return -1;
}

int main(void)
{
    while(cin >> star >> end)
    {
        if(star >= end)             //***如果star>=end,则每次减1,最少需要star-end步
        {
            cout << star - end << endl;
            continue;
        }
        memset(vis, 0, sizeof(vis));  //***标记数组清0,不然会对后面的测试产生影响
        int ans=bfs(star);            //***深搜
        cout << ans << endl;
    }
    return 0;
}

http://poj.org/problem?id=3278(bfs)