ZOJ 3593.One Person Game【扩展欧几里得+逼近】【4月11】

一人游戏最短路径算法
本文介绍了一款简单的单人游戏挑战,玩家需从起点A到达终点B,并给出了通过算法求解达到目标所需的最少步数的方法。游戏允许玩家每步向左或向右移动特定距离。文章提供了一个C++实现的示例,展示了如何使用扩展欧几里得算法来解决此类问题。

One Person Game

Time Limit: 2 Seconds      Memory Limit: 65536 KB

There is an interesting and simple one person game. Suppose there is a number axis under your feet. You are at point A at first and your aim is point B. There are 6 kinds of operations you can perform in one step. That is to go left or right by a,b and c, here c always equals to a+b.

You must arrive B as soon as possible. Please calculate the minimum number of steps.

Input

There are multiple test cases. The first line of input is an integer T(0 < T ≤ 1000) indicates the number of test cases. Then T test cases follow. Each test case is represented by a line containing four integers 4 integers ABa and b, separated by spaces. (-231 ≤ AB < 231, 0 < ab < 231)

Output

For each test case, output the minimum number of steps. If it's impossible to reach point B, output "-1" instead.

Sample Input

2
0 1 1 2
0 1 2 4

Sample Output

1
-1

根据题意,很容易知道要算 a*x+b*y = B-A中的x,y。但是解出来是一组特解,需要让x,y向0逼近

#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
typedef long long LL;
const LL INF = 0x3f3f3f3f;
LL e_gcd(LL a, LL b, LL &x, LL &y)
{
    if(b == 0)
    {
        x = 1;
        y = 0;
        return a;
    }
    LL r= e_gcd(b, a%b, x, y);
    LL temp = x;
    x = y;
    y = temp - a/b*y;
    return r;
}
int main()
{
    LL T, A, B, a, b;
    scanf("%lld", &T);
    while(T--)
    {
        LL x, y, m;
        scanf("%lld %lld %lld %lld", &A, &B, &a, &b);
        LL GCD = e_gcd(a, b, x, y);
        if((B-A)%GCD != 0) cout << -1 << endl;
        else
        {
            a /= GCD;
            b /= GCD;
            x = (B-A)/GCD*x;
            y = (B-A)/GCD*y;
            LL ans = INF*INF;
            LL t = (y-x)/(a+b);
            for(LL i = t-1;i <= t+1; ++i)
            {
                if((abs(x + b*i) + abs(y - a*i)) == abs(x + b*i + y - a*i))//同号
                {
                    m = max(abs(x+b*i), abs(y-a*i));
                }
                else m = abs(x+b*i) + abs(y-a*i);//异号
                ans = min(ans, m);
            }
            cout << ans << endl;
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值