UVa:846 - Steps

本文介绍了一种计算在平面直角坐标系中从一点到另一点所需最短步数的方法,考虑到每一步的长度只能增加或减少1或者保持不变的约束条件。通过数学公式与算法实现,给出了具体的计算步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注意:“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间的距离每步的步长总步数
000
111
21 12
31 1 13
41 2 13
51 2 1 14
61 2 2 14
71 2 2 1 15
81 2 2 2 15
91 2 3 2 15
101 2 3 2 1 16
111 2 3 2 2 16
121 2 3 3 2 16
131 2 3 3 2 1 17
141 2 3 3 2 2 17
151 2 3 3 3 2 17
161 2 3 4 3 2 17

步长最长为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<stdio.h>
#include<math.h>
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!

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值