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
题意:从A点到B点 有3种移动方式 移动 a距离,b距离或者 a+b距离,问最少需要多少步。
分析:
有3种情况
ax+by=A-B
ax+cy=A-B
bx+cy=A-B
用扩展欧几里德很容易求出 x和y的值
X=x+b/gcd *t
Y=y-a/gcd *t
通过这两个方程可以得到两个关于t的线,两个的斜率互异
我们要求的是 |X|+|Y|的最小值
所以最小值应该在 X=0或者Y=0处可以取到
但是这里的X和Y是经过整除运算得到的,所以存在误差
在计算的时候需要多查看左一位和右一位
AC代码:
#include<stdio.h> #include<string.h> #include<math.h> #include<algorithm> using namespace std; long long kzgcd(long long a,long long b,long long &x,long long &y) { if(b==0) { x=1,y=0; return a; } long long ans=kzgcd(b,a%b,x,y); long long t=x; x=y; y=t-(a/b)*y; return ans; } long long solve(long long a,long long b,long long c) { long long x,y; long long gcd=kzgcd(a,b,x,y); if(c%gcd) return -1; x=x*c/gcd; y=y*c/gcd; long long aa=a/gcd; long long bb=b/gcd; //x=x0+b/gcd *t y=y0-a/gcd *t; long long ans=abs(x)+abs(y); for(long long i=-x/bb-1;i<=-x/bb+1;i++) { long long xx=x+bb*i; long long yy=y-aa*i; if(ans>abs(xx)+abs(yy)) ans=abs(xx)+abs(yy); } for(long long i=y/aa-1;i<=y/aa+1;i++) { long long xx=x+bb*i; long long yy=y-aa*i; if(ans>abs(xx)+abs(yy)) ans=abs(xx)+abs(yy); } return ans; } int main() { int T; scanf("%d",&T); while(T--) { long long A,B,a,b; scanf("%lld%lld%lld%lld",&A,&B,&a,&b); long long C=abs(A-B),c=a+b,ans[4]; ans[1]=solve(a,b,C); ans[2]=solve(a,c,C); ans[3]=solve(b,c,C); if(ans[1]==-1&&ans[2]==-1&&ans[3]==-1) printf("-1\n"); else { long long anss=ans[1]; for(int i=2;i<=3;i++) anss=min(anss,ans[i]); printf("%lld\n",anss); } } }