POJ3278Catch That Cow简单一维广搜

Catch That Cow

Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 61758   Accepted: 19306

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.

Source


USACO 2007 Open Silver

[Submit]   [Go Back]   [Status]   [Discuss]

 
  题意:
  你在一个一维坐标的n位置,牛在k位置,你要从n到k,抓到那头牛。你可以有三种走法,n+1,n-1,或者n*2直接跳。求你抓到那头牛的最短步数。
  思路:
  简单广搜的思想。状态跳转的时候有三种跳转的方式,将新的状态放到队列中,再不断提取队列中最前面的状态,直到找到k位置。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int n,k;
int visit[100005];
int mark[100005];
int t;
struct nodes
{
    int x;
    int m;
};
nodes node1,node2;
void bfs()
{
    queue<nodes> q;
    while(!q.empty())
    q.pop();
    node1.x=n;
    node1.m=0;
    q.push(node1);
    while(!q.empty())
    {
        node1=q.front();
        q.pop();
        if(visit[node1.x]==k)
        {
            cout<<node1.m<<endl;
             break;
        }

        node2.x=node1.x+1;
        if(node2.x>=0&&node2.x<=100000&&!mark[node2.x])
        {
            mark[node2.x]=1;
            node2.m=node1.m+1;
            q.push(node2);
        }
        node2.x=node1.x-1;
       if(node2.x>=0&&node2.x<=100000&&!mark[node2.x])
        {
            mark[node2.x]=1;
            node2.m=node1.m+1;
            q.push(node2);
        }
        node2.x=node1.x*2;
        if(node2.x>=0&&node2.x<=100000&&!mark[node2.x])
        {
            mark[node2.x]=1;
            node2.m=node1.m+1;
            q.push(node2);
        }
    }
}
int main()
{
    while(~scanf("%d%d",&n,&k))
    {
        memset(visit,-1,sizeof(visit));
        memset(mark,0,sizeof(mark));
        visit[k]=k;
        mark[n]=1;
        bfs();
    }
}

 

posted @ 2015-08-22 15:50  Lincy*_*  阅读(179)  评论(0编辑  收藏  举报