题解:One Person Game(扩展gcd,求|X|+|Y|最小值)

这是一个有趣的一人游戏,玩家初始位于数轴上的点A,目标是到达点B。允许进行6种操作,向左或向右移动a、b或a+b的距离。目标是最小化到达B所需的步骤数。输入包含多个测试用例,每个用例给出A、B、a和b的值。输出每个测试用例的最小步骤数,若无法到达B则输出"-1"。问题转化为找到满足ax+by=|B-A|且|x|+|y|最小的整数解。

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

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 A, B, a and b, separated by spaces. (-231 ≤ A, B < 231, 0 < a, b < 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


满足ax+by=|B-A|
|x|+|y|最小值

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
const ll inf = 0x3f3f3f3f;
void exgcd(ll a,ll b,ll&g,ll&x,ll&y)//g:gcd(a,b)
{
 if(b==0)
 {
  x=1;y=0;g=a;return;
 }
 exgcd(b,a%b,g,y,x);
 y-=(a/b)*x;
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        ll A,B,C,a,b;
        cin>>A>>B>>a>>b;
        ll x,y;
        ll r;
        exgcd(a,b,r,x,y);
        C=B-A;
        if(C%r)
            cout<<"-1"<<endl;
        else
        {
            x*=(C/r);
            y*=(C/r);
            a/=r;
            b/=r;
            ll ans=inf*inf,tmp;
            ll mid=(y-x)/(a + b);//x|+|y|最小值在x=x+bt与y=y-at两条直线交点附近;
            for(ll T=mid-1;T<=(mid+1);T++)
            {
                if((x+b*T)*(y-a*T)>=0)//同方向 ,可合并 
                {
                    tmp=max(abs(x+b*T),abs(y-a*T));
                }
                else// 
                    tmp=abs(x-y+(a+b)*T);
                ans=min(ans,tmp);
            }
            cout<<ans<<'\n';
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值