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
题解:
若能到达则一定存在整数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;
}