ZOJ 3593 One Person Game(扩展欧几里得求最小步数)

本文介绍了一款一人数轴游戏的算法解决方案。玩家需要从起点A抵达终点B,每一步可以选择向左或向右移动特定的距离。文章详细阐述了如何判断是否能够达到目标位置,并给出最小步数的具体算法实现。

摘要生成于 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 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

题解:
若能到达则一定存在整数x,y,z使得a*x+b*y+c*z=|A-B|;
即a*(x+z)+b*(y+z)=|A-B|;即a*x+b*y=|A-B|;
因此可求解 a*x+b*y=gcd(a,b),若|A-B|%gcd(a,b)==0则有解,
否则无解。若有解,通过扩展欧几里得求出的x0,y0通过整理
便得到此题得一组解 x0=x0*|A-B|/gcd; y0=y0*|A-B|/gcd;
而此题要求步数最少,因此需要求出解的通式:
x=x0+b*t/gcd
y=y0-a*t/gcd 其中t为任意整数。
t可以任取,因此便有无数对(x,y)的解使a*x+b*y=|A-B|成立。
而当x==y时便是最优。由此可求出t,但是此时的t不一定是
整数,因此枚举t附近的整数找出最优解即可

代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll exten_gcd(ll a,ll b,ll& x,ll& y)
{
    ll d=a;
    if(b)
    {
        d=exten_gcd(b,a%b,y,x);
        y-=a/b*x;
    }
    else x=1,y=0;
    return d;
}
ll cal(ll a,ll b,ll c)
{
    ll x,y;
    ll gcd=exten_gcd(a,b,x,y);
    if(c%gcd!=0)return -1;
    x=x*(c/gcd);
    y=y*(c/gcd);
    ll ans=1e15+7,t;
    t=(y-x)*gcd/(a+b);
    t=t-3;
    for(int i=0;i<7;i++,t++)
    {
        ll x1=x+b*t/gcd;
        ll y1=y-a*t/gcd;
        if(x1*y1>0)
            ans=min(ans,max(abs(x1),abs(y1)));
        else ans=min(ans,abs(x1-y1));
    }
    return ans;
}
int main()
{
    int T;scanf("%d",&T);
    while(T--)
    {
        ll A,B,a,b;
        scanf("%lld%lld%lld%lld",&A,&B,&a,&b);
        ll s=cal(a,b,abs(A-B));
        printf("%lld\n",s);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值