Steps——找规律

  Steps 

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 and Output 

Input consists of a line containing n, the number of test cases. For each test case, a line follows with two integers:  0$ \le$x$ \le$y < 231 . 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


题意:给定水平坐标轴上的两个位置,从一个位置走到另一个位置,第一步和最后一步长度都为1,中间的步子长度一定是比见面大1,或是相等,或是小1,求最少的步数。

注意,当两个数相等的时候,输出步数为0。

解析:很显然,这是一道找规律的题目,现在推一下规律:

两者之差 走法 步数

1 1 1

2 11 2

3 111 3

4 121 3

5 1211 4

6 1221 4

7 12211 5

8 12221 5

9 12321 5

10 123211 6

11 123221 6

12 123321 6

13 1233211 7

14 1233221 7

15 1233321 7

16 1234321 7

17 12343211 8

18 12343221 8

19 12343321 8

20 12344321 8

21 123443211 9

22 123443211 9

23 123443321 9

24 123444321 9

25 123454321 9

26 1234543211 10


由上表可知随着两者之差的增大,步数一次为1个1 , 1个2 ;2个3 , 2个4 ;3个5 , 3个6 ;4个7 , 4个8 ;5个9 , 5个10 ;6个11 , 6个12 ;7个13 , 7个14 ;8个15 , 8个16 ;9个17 , 9个18 。。。。。


1,2项合并,3, 4项合并,5, 6项合并。。。。,得到等差数列:


2,4,6,8,10,12,14.。。。。。,

该等差数列中每一个数代表合并的两项中包含的数的个数(即差的个数);

前n项和代表前n项所包含的差的总个数


这样一来,我们就可以根据两项的差找到所需最小步数最大可能在的位置。

即计算前n项和最先大于或等于差的位置,即下标,很巧的是,求出来的下标代表了原来合并的那两项所包含的的差的数目的一半。

根据求出来的下标计算该区间内的最小可能差,然后用题目中给的差减去最小可能差,求出区间内的步数。

#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;

int main()
{
    int a,b,cha,sum,zx;
    int i,j,k,n;
    scanf("%d",&k);
    while(k--)
    {
        scanf("%d%d",&a,&b);
        cha = b - a;
        if(cha == 0)
            printf("0\n");
        else
        {
            for(i = 1; i <= 10000; i++)
            {
                if(2 * i + i * (i - 1) >= cha)
                    break;
            }
            n = i;
            sum = 2 * n + n * (n - 1);
            zx = sum - 2 * n;
            j = 2 + (n - 1) * 2;//合并区间内最大步数
            if(cha - zx > n)
            {
                printf("%d\n",j);
            }
            else
                printf("%d\n",j - 1);
        }
    }
    return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值