ZOJ - 3593 One Person Game (扩展欧几里德)

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 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点 有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);
		}
	} 
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值