uva 846 - Steps

找出步數與距離的關係即可得解。

  • 0步最多能抵達的距離是0
  • 1步最多能抵達的距離是1(1)
  • 2步最多能抵達的距離是2(1 1)
  • 3步最多能抵達的距離是4(1 2 1)
  • 4步最多能抵達的距離是6(1 2 2 1)
  • 5步最多能抵達的距離是9(1 2 3 2 1)
  • 6步最多能抵達的距離是12(1 2 3 3 2 1)
  • ……以此類推
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cmath>
 4 #define ERROR 1e-10
 5 using namespace std;
 6 int main(){
 7     int n, x, y;
 8     int dis, step;
 9     while( scanf( "%d", &n ) != EOF ){
10         for( int i = 0 ; i < n ; i++ ){
11             scanf( "%d%d", &x, &y );
12 
13             dis = y-x;
14             if( dis == 0 ){
15                 printf( "0\n" );
16                 continue;
17             }
18 
19             step = (int)(sqrt((double)dis)+ERROR);
20             if( step * step == dis ) step = step * 2 - 1;
21             else if( step * step + step < dis ) step = step * 2 + 1;
22             else step = step * 2;
23 
24             printf( "%d\n", step );
25         }
26     }
27     return 0;
28 }

另:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 int main()
 5 {
 6     int x, y;
 7     int testCases;
 8     int min_steps = 0;
 9     cin >> testCases;
10     while(testCases --)
11     {
12         cin >> x >> y;
13         int difference = y - x;
14         min_steps = 0;
15 
16         if(difference != 0)
17         {
18             int sumOfSteps = 0;
19             int z = 2; //divided by 2, it represents the size if the next step
20 
21             while(difference > sumOfSteps)
22             {
23                 sumOfSteps += (z / 2); // next step
24                 min_steps ++;
25                 z++;
26             }
27         }
28         cout << min_steps << endl;
29     }
30     return 0;
31 }

 

 1 #include<cstdio>
 2 #include<cmath>  
 3 
 4 int main(void)
 5 {
 6     int t, x, y, diff, n;
 7     scanf("%d", &t);
 8     while (t--)
 9     {
10         scanf("%d%d", &x, &y);
11         diff = y - x;
12         if (diff == 0)
13             puts("0");
14         else
15         {
16             n = (int)sqrt(diff);
17             diff -= n * n;
18             if (diff == 0)
19                 printf("%d\n", (n << 1) - 1);
20             else if (diff <= n)
21                 printf("%d\n", n << 1);
22             else
23                 printf("%d\n", (n << 1) + 1);
24         }
25     }
26     return 0;
27 }  

 

转载于:https://www.cnblogs.com/aze-003/p/5143222.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值