hdu2717 为什么用递推会超时?

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
 
题意:抓牛,牛在k点,从n点开始,可以先前一步(n-1)向后一步(n+1)和跳一倍(2*n),问最少多少不抓到牛。
思路:我觉得这题可以用dp算法,因为从i点是奇数就是(i-1)和(i+1)中最小的。i是偶数就从(i-1)(i+1)(i/2)中找最小的。所以代码入下:
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int dp[100003];
int Min(int &i,int &j,int k=9000000)
{
    int MIN;
    if(i>j)
        MIN=j;
    else
        MIN=i;
    if(MIN>k)
        MIN=k;
    return MIN;
}
int main()
{
    int m,n;
    while(~scanf("%d%d",&m,&n))
    {
        memset(dp,9000000,sizeof(dp));
        for(int i=0;i<=m;i++)
            {
                dp[i]=m-i;
                if(i!=0)
                dp[i<<1]=dp[i]+1;
            }
            for(int j=m+1;j<n+1;j++)
        {
            if(2*j<n)
            dp[j<<1]=dp[j]+1;
            if(j&1==1)
            dp[j]=Min(dp[j+1],dp[j-1])+1;
            else
            dp[j]=Min(dp[j+1],dp[j-1],dp[j/2])+1;
        }
        printf("%d\n",dp[n]);
    }
}

但是这种代码是超时的。最后看了下题解,发现是用广搜。现在对广搜海有点不熟悉。先记下了以后再看,再对比下两种算法的优劣度。

posted @ 2018-11-18 19:56  简单的也不会啊  阅读(161)  评论(0编辑  收藏  举报