UVa 846 Steps (数学)2014-07-14 csdn博客 synapse7846 - StepsTime limit: 3.000 secondshttp://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=99&page=show_problem&problem=787One 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
x
y < 2
31. For each test case, print a line giving the minimum number of steps to get from
xto
y.
Sample Input
345 4845 4945 50
Sample Output
334
自己算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 << 1) - 1);else if (diff <= n)printf("%d
", n << 1);elseprintf("%d
", (n << 1) + 1);}}return 0;}