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: 0Sample 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;
}

本文介绍了解决UVA 846 Steps问题的一种高效算法,该问题要求找到从整数坐标x到y的最短步数,每一步长度必须为非负数,并且只能比前一步长1、相等或短1,首尾步长固定为1。文章提供了一种基于平方根的方法来快速求解,并附带完整的C语言代码实现。
988

被折叠的 条评论
为什么被折叠?



