POJ-2590-Steps题目详解,思路分析及代码,规律题,重要的是找到规律~~

Steps
Time Limit: 1000MS Memory Limit: 65536K
   

http://poj.org/problem?id=2590

Description

One steps through integer points of the straight line. The length of a step must be nonnegative and can be by one bigger than, equal to, or by one smaller than the length of the previous step. 
What is the minimum number of steps in order to get from x to y? The length of the first and the last step must be 1.

Input

Input consists of a line containing n, the number of test cases.

Output

For each test case, a line follows with two integers: 0 <= x <= y < 2^31. For each test case, print a line giving the minimum number of steps to get from x to y.

Sample Input

3
45 48
45 49
45 50

Sample Output

3
3
4

Source


    题目意思很好懂:求x点到y点的最小步数,起始和结束的都只能走一步,中间的可以等于前一步,可以比前一步大一或小一;

 我们可以推算出,假设走n步,所能达到的最长距离为:1+2+3+4+...+(n+1)/2+...+4+3+2+1;明白了吧,1  2  3  4  5 ...(n+1)/2... 5  4  3  2  1   ;是不是很熟悉;;

步数(n):        最大距离                                                        f(n)       

 1                 1                                                                         f(1)=1;

 2                 1 + 1                                                                   f(2)=2=f(1)+(2+1)/2;

 3                 1 + 2 + 1                                                             f(3)=4=f(2)+(3+1)/2;

...                   ...                                                                        ...

 n                  1 + 2 + 3 +...+ (n+1)/2 +...+ 3 + 2 +1               f(n)=f(n-1)+(n+1)/2;

这样的话方法就多了,可以把距离与步数的关系打表,然后算出距离差,二分查找即可,但开始我有个疑问,如果这个差值介于f(n)与f(n-1)之间怎么办,我们知道n-1步所能达到的最大距离是f(n-1),如果f(n-1)还比差值小,那么无论如何n-1步都是无法达到的,即只能在n步达到;


   这里介绍一种很好的方法,代码简洁易懂,思路都差不多;

     

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
int find(int x)
{
    int i,a=1;
    for(i=2;;i++)
    {
        a+=(i+1)/2;//a为i步能达到的最大距离,这样连打表都不用了;
        if(a>=x)
            break;
    }
    return i;
}
int main()
{
    int t,a,b;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&a,&b);
        if(b-a<=3)
            printf("%d\n",b-a);//革除了a b 相等的情况;
        else
            printf("%d\n",find(b-a));
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值