ZOJ

来源:互联网 发布:知乎发现更大的世界 编辑:程序博客网 时间:2024/06/02 03:17

题意:给定两个点A,B,和a,b;c=a+b。由A走到B,每步可以向左或向右走a,b,c,,步;求最小步数

思路:ax+by+cz=B-A ==> a(x+z)+b(y+z)=B-A ==> ax+by=B-A

当x0,y0同号时,步数=x0+y0-min(x0,y0)(转化成走c步)=max(x0,y0)

当x0,y0异号时,步数=absx0)+abs(y0(无法转化成走c步)

正确解法是x与y最接近时,步数最小;

通解 x=x0+b*t;

        y=y0-a*t;

当x0,y0同号时,改变t的值,假如x增大,y一定减少,max(x,y)会增大,所以x,y最接近时,max(x,y)最小

当x0,y0异号时,因为x,y最接近,我猜测是x0,y0最靠近0的时候,(因为我推不出来,如果有大佬会推,请给我评论留言

x=y时,t=(y0-x0)/(a+b),考虑不能整除的情况,算t的左右值代入

#include<cstdio>#include<iostream>#include<cstring>#include<algorithm>#include<cmath>using namespace std;typedef long long ll;ll egcd(ll a,ll b,ll &x,ll &y){    if(b==0){        x=1,y=0;        return a;    }    ll d=egcd(b,a%b,y,x);    y-=a/b*x;    return d;}int main(){    ll t,a0,b0,a,b,d,x,y,k;    scanf("%lld",&t);    while(t--)    {        scanf("%lld%lld%lld%lld",&a0,&b0,&a,&b);        ll c=abs(b0-a0);        d=egcd(a,b,x,y);        if(c%d) {printf("-1\n");continue;}        a/=d;b/=d;        x=c/d*x;y=c/d*y;        k=(y-x)/(a+b);        ll ans=10000000000;        for(int i=k-1;i<=k+1;i++)        {           ll  x0=x+b*i,y0=y-a*i;           if(abs(x0)+abs(y0)==abs(x0+y0)) ans=min(ans,max(x0,y0));            else ans=min(ans,abs(x0)+abs(y0));        }        cout<<ans<<endl;    }    return 0;}

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,band 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)

<h4< dd="">
Output

For each test case, output the minimum number of steps. If it's impossible to reach point B, output "-1" instead.

<h4< dd="">
Sample Input

20 1 1 20 1 2 4

<h4< dd="">
Sample Output

1-1


原创粉丝点击