ZOJ 3593.One Person Game 扩展欧几里得+逼近



Description

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, herec 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和B两个地方,现在从A到B,每次可以向任意方向走a、b或者c的距离,其中c=a+b,问能不能走到B,能的话最少走几次。

首先可以推出这个式子:a*x+b*y+c*z=|B-A|然后又因为c=a+b,所以其实可以化成a*x+b*y=|B-A|。所以需要用扩展gcd求出x,y,但是这个x,y有可能不是最优的,为什么呢?为了让步数最小就要拉近x,y的距离,使|x-y|最小。怎么拉近,

下面来看通解方程:

 x = x0 + (b/gcd)*t

 y = y0 – (a/gcd)*t 

实际上是关于x,y关于t的两条直线(他们必有交叉点)。

可以设x==y,然后解出那个对应的t

,得到此时的一组解(t=(y0-x0)/((a+b)/gcd))但是实际上有可能无法使x==y(没有整数t),所以算出来的t接近于交叉点的t(有可能是小数),所以可能也不是最优解,所以需要增加一次t+1,t-1,这样比较3个t得到的结果x,y同为正或同为负时,绝对值大的那个值(c的存在,a和b合并为c),一正一负就是绝对值和,其中小的一个必是最优解。



#include<iostream>
#include<cstring>
#include<cmath>
#define LL long long
#define inf 999999999999999999
using namespace std;
void extendgcd(LL a,LL b,LL &d,LL &x,LL &y)
{
    if(!b)
    {
        d=a;
        x=1;
        y=0;
    }
    else
    {
        extendgcd(b,a%b,d,y,x);
        y-=x*(a/b);
    }
}
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        LL A,B,a,b;
        cin>>A>>B>>a>>b;
        LL c=B-A;
        LL x0,y0,gcd;
        extendgcd(a,b,gcd,x0,y0);
        if(c%gcd!=0)
        {
            cout<<-1<<endl;
            continue;
        }
        x0=c/gcd*x0;
        y0=c/gcd*y0;
        LL t=(y0-x0)/(a/gcd+b/gcd);
        LL ans=inf;
        for(LL i=t-1;i<=t+1;i++)
        {
            LL tx=x0+(b/gcd)*i;
            LL ty=y0-(a/gcd)*i;
            LL x;
            if(abs(tx)+abs(ty)==abs(tx+ty))
                x=max(abs(tx),abs(ty));
            else
                x=abs(tx)+abs(ty);
            ans=min(ans,x);
        }
        cout<<ans<<endl;
    }
    return 0;
}


你可能感兴趣的:(拓展欧几里德算法)