首页 > 代码库 > [ACM] hdu 2717 Catch That Cow (BFS)

[ACM] hdu 2717 Catch That Cow (BFS)

Catch That Cow



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.
 

Source
USACO 2007 Open Silver


解题思路:

从位置n到位置k根据规则最少走几步可以到达,规则是从n可以走到n-1,可以走到n+1,也可以走到n*2.用bfs广搜来做,vis[]用来记录是否访问,hash[]用来记录走的步数。

遇到的问题有数组越界,一定要先判断n*2,n-1,n+1是否越界,还有问题就是步数的保存,因为很多节点都是同一个步数下的状态,因为每一步根据规则可以衍生出三种状态。所以用hash[ q.front() 下一个状态]=hash[q.front()]+1.用这种方法来记录步数,最后直接输出hash[k]就可以了。

代码:

#include <iostream>
#include <string.h>
#include <queue>
using namespace std;
const int len=100000;
int hash[len+10];//hash[i]用来保存走到位置i时是第几步
bool vis[len+10];
int n,k;

void bfs()
{
    memset(vis,0,sizeof(vis));
    queue<int>q;
    q.push(n);
    vis[n]=1;
    hash[n]=0;
    while(!q.empty())
    {
        int temp=q.front();
        q.pop();
        if(temp+1==k||temp-1==k||temp*2==k)//找到
        {
            hash[k]=hash[temp]+1;
            break;
        }
        if(temp-1>=0&&!vis[temp-1])
        {
            q.push(temp-1);
            vis[temp-1]=1;
            hash[temp-1]=hash[temp]+1;
        }
        if(temp+1<=len&&!vis[temp+1])
        {
            q.push(temp+1);
            vis[temp+1]=1;
            hash[temp+1]=hash[temp]+1;
        }
        if(temp*2<=len&&!vis[temp*2])
        {
            q.push(temp*2);
            vis[temp*2]=1;
            hash[temp*2]=hash[temp]+1;
        }
    }
}

int main()
{
    while(cin>>n>>k)
    {
        if(n==k)
        {
            cout<<0<<endl;
            continue;
        }
        else
            bfs();
        cout<<hash[k]<<endl;
    }
    return 0;
}