码迷,mamicode.com
首页 > 其他好文 > 详细

ZOJ 3593 One Person Game

时间:2014-05-24 07:02:17      阅读:310      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   c   code   java   

One Person Game

Time Limit: 2 Seconds      Memory Limit: 65536 KB

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 integersABa 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

bubuko.com,布布扣
#include<iostream>
#include<stdio.h>
#include<cstring>
#include<cstdlib>
#include<math.h>
using namespace std;
typedef long long LL;


LL Ex_GCD(LL a,LL b,LL &x,LL &y)
{
    if(b==0)
    {
        x=1;
        y=0;
        return a;
    }
    LL g=Ex_GCD(b,a%b,x,y);
    LL hxl=x-(a/b)*y;
    x=y;
    y=hxl;
    return g;
}
LL get(LL a,LL b)
{
    if(a*b<0)
    {
        return abs(a)+abs(b);
    }
    else return abs(a)>abs(b)? abs(a):abs(b);
}
int main()
{
    int T;
    LL A,B,a,b,g,x,y,ans,cur,c;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%lld%lld%lld%lld",&A,&B,&a,&b);
        g=Ex_GCD(a,b,x,y);
        c=A-B;
        if(c<0) c=-c;
        if(c%g!=0)
        {
            printf("-1\n");
            continue;
        }
        a=a/g;
        b=b/g;
        x=x*(c/g);
        y=y*(c/g);

        double t = (y-x)*1.0/(a+b);
        LL  K = (LL)t;

        cur = get(x+b*K,y-a*K);
        ans=cur;

        K++;
        cur=get(x+b*K,y-a*K);
        ans=min(ans,cur);

        K++;
        cur=get(x+b*K,y-a*K);
        ans=min(ans,cur);

        K=K-3;
        cur=get(x+b*K,y-a*K);
        ans=min(ans,cur);

        K=K-1;
        cur=get(x+b*K,y-a*K);
        ans=min(ans,cur);

        printf("%lld\n",ans);

    }
    return 0;
}
bubuko.com,布布扣

 

ZOJ 3593 One Person Game,布布扣,bubuko.com

ZOJ 3593 One Person Game

标签:style   class   blog   c   code   java   

原文地址:http://www.cnblogs.com/tom987690183/p/3736363.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!