uva 846

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

  • 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
" );
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
", 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 << 1) - 1);
20             else if (diff <= n)
21                 printf("%d
", n << 1);
22             else
23                 printf("%d
", (n << 1) + 1);
24         }
25     }
26     return 0;
27 }  
原文地址:https://www.cnblogs.com/aze-003/p/5143222.html