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: 0x
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
找规律
1: 1
2 1 1
3 1 1 1
4: 1 2 1
5 1 2 1 1
6 1 2 2 1
7 1 2 2 1 1
8 1 2 2 2 1
9: 1 2 3 2 1
10 1 2 3 2 1 1
11 1 2 3 2 2 1
12 1 2 3 3 2 1
13 1 2 3 3 2 1 1
14 1 2 3 3 2 2 1
15 1 2 3 3 3 2 1
16: 1 2 3 4 3 2 1
n*n:2*n-1
N*N-(N-1)*(N-1)-1
2*n-2
因为完全平方数的最小step是确定的所以,以完全平方数为界限。
n*n: 1......n......1 minstep:2*n-1
.
.
n*(n+1) 1.....n,n.......1 minstep:2*n
.
.
(n+1)*(n+1) :1......n+1.........1 minstep:2*n+1
确定好分界线,忘记了0应该输出0,wrong了一次(Y-Y);
#include <stdio.h>
#include <math.h>
void main()
{int T,x,y,z,a;
scanf("%d",&T);
while (T--)
{scanf("%d%d",&x,&y);
if (y==x) printf("0");
else
{
z=sqrt(y-x);
if (z*z==y-x) printf("%d",2*z-1);
else {a=z*z+z;if (y-x>a) printf("%d",2*z+1); else printf("%d",2*z);}
}
printf("\n");
}
}