poj2590steps数列递推

Problem D: Step by step
Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 23 Solved: 6
[Submit][Status][Web Board]
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 consists of a line containing n, the number of test cases. 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.

Input
Output
Sample Input
3
45 48
45 49
45 50
Sample Output
3
3
4
题目大意:
有一条线段,坐标为x,y。然后从x走到y最少的步数是多少,每次走的步的长度有两个限制:
(1)第一步和最后一步是长度为1。
(2)当前走的步数的长度比上一步长度多1,或者等于上一步长度,或者比上一步长度少1。

分析:可以拆成两个对称的等差数列,差为1,先递增后递减是最小的步数
利用等差数列的公式可以求出项数
公式:(1 + t ) * t / 2 = 和。
知道和应该是(m - n ) / 2,因为拆成两个等差数列。
求出项数t之后分三种情况
1.和正好是2 * t步
2.和小于等于 (1 + t) * t / 2 * 2 + (t + 1) 也就是2*t+1步
3.和大于上一个的条件。也就是2 * t+2步(2*t+2步一定能走完,因为求出来的t一定满足和大于等于走t步的和,小于走t+1步的和,如果等于,解方程结出来的是t+1,t+1步和比t步多走了2* (t + 1)步,第三种情况需要多走的步数大于t+1(小于等于t+1是第二种情况),小于2 * (t + 1) - 1, 所以两步一定会走完。所以应该走2 * t + 2步
代码中注释太乱,放到上面了:
/*三种情况
1. 恰好 1 2 2 1的情况
2. 1 2 1 1 情况,这种情况例子,5,求出num = 1,因为num = 2 时候 (1 + 2) * 2 > 5,所以解是1.然而1 1 < 5, 1 2 1 < 5
所以不能简单的num * 2 + 1,要先判断 1 + 1 + 2 够不够,不够num还要加上一位。
3.恰好是 1 2 3 2 1
*/

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(void)
{
    int T;
    int n, m, sub, num;

    scanf("%d", &T);
    while (T--)
    {
        scanf("%d %d", &n, &m);
        sub = m - n;
        if (sub == 0 || sub == 1)
        {
            printf("%d\n", sub);
            continue;
        }
        num = (-1.0 + sqrt(1 + 4 * sub)) / 2.0;
        if (num * num + num == sub) num *= 2;
        else if (num * num + num + num + 1 < sub) num = num *2 + 2;
        else num = num * 2 + 1;
        printf("%d\n", num);
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值