[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;
    }







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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值