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



HintThe 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


思路

考验对状态的理解,每次走下一步有3种状态,bfs即可

代码

#include<bits/stdc++.h>
using namespace std;
const int d[3] = {1,-1,0};
struct node
{
    int pos;
    int step;
};
int n,k;
bool vis[200010];

bool judge(int x)
{
    if(vis[x] || x<0 || x>100000)
        return false;
    return true;
}
int bfs(node st)
{
    queue<node> q;
    q.push(st);
    node next,now;
    memset(vis,false,sizeof(vis));
    vis[st.pos] = true;
    while(!q.empty())
    {
        now = q.front();
        q.pop();
        if(now.pos == k) return now.step;
        for(int i=0;i<3;i++)
        {
            if(i==0 || i==1)
                next.pos = now.pos + d[i];
            else
                next.pos = now.pos * 2; 
            next.step = now.step + 1; 
            if(judge(next.pos))
            {
                q.push(next);
                vis[next.pos] = true;
            }
        }
    }
}
        
int main()
{
    while(cin>>n>>k)
    {
        node t;
        t.pos = n; t.step = 0;
        int ans = bfs(t);
        cout << ans << endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/MartinLwx/p/9903171.html