2012-03-18 17:49:47Morris

[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

做法 : Greedy
例如
L = 3 => 1+1+1
L = 4 => 1+2+1
L = 5 => 1+2+1+1 ...
#include <stdio.h>
#include <math.h>
int main() {
int t, x, y, L;
scanf("%d", &t);
while(t--) {
scanf("%d %d", &x, &y);
L = y-x;
int steps = 0, n = (int)sqrt(L);
steps = n;
L -= n*(n+1)/2;
while(L > 0) {
while(n*(n+1)/2 > L)
n--;
if(n*(n+1)/2 == L)
L = 0, steps += n;
else
L -= n, steps ++;
}
printf("%d\n", steps);
}
return 0;
}