[1170] 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.
  • 输入
  • This problem has several cases of cases.
    Each case 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.

    这题不知道老蔡怎么做的,长度才100+,我的长度整整1000多

    我找到的规律是
    距离=0  0步
    距离=1  1步//1步的边界
    距离=2  2步//2步的边界
    距离=3  3步
    距离=4  3步//3步的边界
    距离=5  4步
    距离=6  4步//4步的边界
    距离=7  5步
    距离=8  5步
    距离=9  5步//5步的边界
    距离=10  6步
    。。。。。

    所以,把边界拿出来:
      形成数列:
         1 2 4  6 9 12 16 20 25.。。。。。。
    每一次我都去判断一个数是不是完全平方数,若是的话,答案就是2*sqrt(n)-1
    否则,分别往前和往后找完全平方数a和b,又因为每两个完全平方之间有个非完全平方数,这个非完全平方数恰好等于(a+b)/2;
    所以拿当前距离去和(a+b)/2相比,大于它,就是2*sqrt(b)-1;否则是2*sqrt(a)

    #include<stdio.h>
    #include<math.h>
    
    int main()
    {
        int a,b,t;
        while(~scanf("%d",&t))
        {
            while(t--)
            {
                scanf("%d%d",&a,&b);
                int len=b-a,x,y;
                x=len,y=len;
                int temp1=(int)(sqrt(len)),temp2;
                if(temp1*temp1==len) //平方数
                {
                	if(temp1!=0)
                       printf("%d\n",2*temp1-1);
                    else
                       printf("0\n");
                }
                else
                {
                   len++;
                   temp1=(int)(sqrt(len));
                   while(temp1*temp1!=len)
                   {
                      len++;
                      temp1=(int)(sqrt(len));
                   }
                   //往左找平方数
                   x--;
                   temp2=(int)(sqrt(x));
                   while(temp2*temp2!=x)
                   {
                      x--;
                      temp2=(int)(sqrt(x));
                   }
                   if((temp1*temp1+temp2*temp2)/2 < y)
                   {
                  	  printf("%d\n",2*temp1-1);
                   }
                            
                   else
                      printf("%d\n",2*temp2);
                }
            }
        }
        return 0;
    }







你可能感兴趣的:([1170] Steps)