• UVA 846 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
    

     

    。。题意:输入两个数据 star, end 表示起点,终点。起点和终点的差为d=end - star。。一个人从起点开始走。初始步长为1.

    每多走一步。可以步长-1 或 + 1或不变。。要求走到终点且到终点时候步长为1的最小步数。。


    思路:先举个例子。。我们知道。步长肯定是能越大越好。但是由于最后要回归1. 所以只能走 比如 (1 2 3 2 1)、(1 2 3 4 3 2 1) 这样。。这种走法。我们设中间那个值为n(最大步长)。能走的长度值就为 n ^ 2. 走的步数为2 * n - 1如果能找到一个这样的最大步长。

    那么走完这个剩下的距离为 d2 = d - n ^ 2.而在这个最大步长走。一步最多是n。那么其实剩下的距离需要的步数为(d2 / n ) + (d2 % n != 0). (如果按最长步数走到最后还有剩余距离,就要加1)...

    注意这题是2 ^ 31要用longlong啊。。 不要被坑了。。

     

    #include <stdio.h>
    #include <string.h>
    #include <math.h>
    
    int t;
    double star, end;
    long long out;
    long long s;
    int main()
    {
        scanf("%d", &t);
        while (t --)
        {
    	scanf("%lf%lf", &star, &end);
    	if (star == end)
    	{
    	    printf("0
    ");
    	    continue;
    	}
    	long long bu = (long long)sqrt(end - star);
    	s = (long long)(end - star) - (bu * bu);
    	out = s / bu + bu * 2 - 1;
    	s = s % bu;
    	if (s != 0)
    	    out ++;
    	printf("%lld
    ", out);
        }
        return 0;
    }



  • 相关阅读:
    C语言程序设计100例之(12):Eratosthenes筛法求质数
    C语言程序设计100例之(11):求质数
    C语言程序设计100例之(10):最大公约数
    C语言程序设计100例之(9):生理周期
    C语言程序设计100例之(8):尼科彻斯定理
    C语言程序设计100例之(7):级数求和
    C/C++ 内部连接与外部连接
    C/C++ 内存管理问题
    C/C++浮点数的比较
    C/C++规范
  • 原文地址:https://www.cnblogs.com/aukle/p/3228633.html
Copyright © 2020-2023  润新知