HDU 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 Output4HintThe 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.

这题我真的做到去世了,上网搜的AC代码。

花式出错,做成贪心。没有考虑到比如 两者坐标不能互换的问题、后退一格或几格再瞬移可以直接到达目标点。。。以为一直瞬移一直瞬移就可以了。

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int main()
{
    int n,m;
    while(cin>>n>>m)
    {
        queue<int > q;
        
        if(n==m)
        {
            cout<<0<<endl;
            continue;
        }
        q.push(n);
        int cnt[200005];        
        memset(cnt,0,sizeof(cnt));
        int w;
        while(!q.empty())
        {
            w=q.front();            
            if(w-1==m||w+1==m||w*2==m)
            {                
                cout<<cnt[w]+1<<endl;
                break;                
            }
            else
            {
                if(w-1>=0&&cnt[w-1]==0)
                {
                    q.push(w-1);
                    cnt[w-1]=cnt[w]+1;
                }
                
                if(w+1<m&&cnt[w+1]==0)
                {
                    q.push(w+1);
                    cnt[w+1]=cnt[w]+1;
                }
            
                if(w*2<2*m&&cnt[2*w]==0)
                {
                    q.push(w*2);
                    cnt[w*2]=cnt[w]+1;
                }
                
            }
            q.pop();
        }
    }
    return 0;
 }

猜你喜欢

转载自www.cnblogs.com/greenaway07/p/10420479.html