846 - Steps
Time limit: 3.000 seconds
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: 0xy < 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
自己算9~16的步数,答案就看出来了。
完整代码:
/*0.015s*/
#include<cstdio>
#include<cmath>
int main(void)
{
int t, x, y, diff, n;
scanf("%d", &t);
while (t--)
{
scanf("%d%d", &x, &y);
diff = y - x;
if (diff == 0)
puts("0");
else
{
n = (int)sqrt(diff);
diff -= n * n;
if (diff == 0)
printf("%d\n", (n << 1) - 1);
else if (diff <= n)
printf("%d\n", n << 1);
else
printf("%d\n", (n << 1) + 1);
}
}
return 0;
}