UVa:846 - Steps

注意:“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.”相邻两步的步长只能相差1或者相等。

模拟一下,即能找出规律:

x和y间的距离 每步的步长 总步数
0 0 0
1 1 1
2 1 1 2
3 1 1 1 3
4 1 2 1 3
5 1 2 1 1 4
6 1 2 2 1 4
7 1 2 2 1 1 5
8 1 2 2 2 1 5
9 1 2 3 2 1 5
10 1 2 3 2 1 1 6
11 1 2 3 2 2 1 6
12 1 2 3 3 2 1 6
13 1 2 3 3 2 1 1 7
14 1 2 3 3 2 2 1 7
15 1 2 3 3 3 2 1 7
16 1 2 3 4 3 2 1 7

步长最长为n = sqrt[distance(x,y)]。

当n * n == distance(x,y)时,总步数count = 2 * n - 1;

distance(x,y) - n * n <= n时,count = 2 * n;

distance(x,y) - n * n > n时,count = 2 * n + 1;


#include
#include
int main() {
    int c;
    while(scanf("%d", &c) != EOF) {
        while(c--) {
            int x, y;
            scanf("%d %d", &x, &y);
            int distance = y - x;
            int n = sqrt(distance);
            if(distance <= 3)
                printf("%d\n", distance);
            else if(n * n == distance)
                printf("%d\n", 2 * n - 1);
            else if(distance - n * n <= n)
                printf("%d\n", 2 * n);
            else
                printf("%d\n", 2 * n + 1);
        }
    }
    return 0;
}


--------------------------------------------------------------------------------------------

            Keep It Simple,Stupid!

--------------------------------------------------------------------------------------------

你可能感兴趣的:(OJ:UVa,题目分类:数学基础)