Steps

Steps

时间: 1ms        内存:64M

描述:

Consider the process of stepping from integer x to integer y along integer points of the straight line. The length of each step must be non-negative and can be one bigger than, equal to, or 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 both the first and the last step must be 1.

输入:

The input begins with a line containing n, the number of test cases. Each test case that follows consists of a line with two integers: 0<=x<=y <231.

输出:

For each test case, print a line giving the minimum number of steps to get from x to y

示例输入:

3
45 48
45 49
45 50

示例输出:

3
3
4

提示:

参考答案(内存最优[748]):

#include <stdio.h>
int main()
{
    long x,y,n,i;
    scanf("%ld",&n);
    while(n--)
    {
        scanf("%ld%ld",&x,&y);
        x=y-x;
        if(x<=3)
        {
            printf("%ld\n",x);
            continue;
        }
        for(i=2;;i++)
        {
            if(i*i==x)
            {
                printf("%ld\n",2*i-1);
                break;
            }
            else if(x>i*i&&x<=i*(i+1))
            {
                printf("%ld\n",2*i);
                break;
            }
            else if(x>i*(i+1)&&x<=(i+1)*(i+1))
            {
                printf("%ld\n",2*i+1);
                break;
            }
        }
    }
    return 0;
}

参考答案(时间最优[20]):

#include<iostream>
using namespace std;
int main()
{
    long a,b,d;
    int n,c,step;
    cin>>n;
    while(n--)
    {
        cin>>a>>b;
        d=b-a,c=1,step=0;
        while(1)
        {
            if(d<2*c)break;
            else
            {
                d=d-2*c;
                step+=2;
                c++;
            }
        }
        if(d>c)step+=2;
        else if(d<=0)step+=0;
        else step+=1;
        cout<<step<<endl;
    }
    return 0;
}

题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注