题目链接:
ZOJ 2593 One Person Game
题意:
有两个点A,B,每次可以选择向左或向右走a,b,c(c = a + b)步,问最少需要多少次从A走向B?
分析:
假设走a步和走b步的次数各为x,y,则可以得到:A + x * a + b * y = B.可以利用扩展欧几里德求出这个二元一次不定方程的一组基础解。我们需要的是C = |x| + |y|的最小值。当x,y符号相同时可以利用一次走c步得到应是取max(abs(x), abs(y)).当x,y符号相异时就应该取abs(x) + abs(y).但是显然x, y有无数组解,那么哪组解答案是最优的呢?
假设基础解为(x0, y0),那么通解可以表示为:x = x0 + k * b, y = y0 - k * a(k ∈ Z)。
如果令x = 0得:k = -x0 / b…①,令y = 0得:k = y0 / a…②当两者同时满足并根据分数的性质:a / b = c / d = (a + c) / (b + d)可得: k = (y0 - x0) / (b + a),但是考虑到这个数的真实值可能为浮点数,需要左右考虑。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <climits>
#include <cmath>
#include <ctime>
#include <cassert>
#define IOS ios_base::sync_with_stdio(0); cin.tie(0);
using namespace std;
typedef long long ll;
int T;
ll ex_gcd(ll a, ll b, ll& x, ll& y)
{
if(b == 0) {
x = 1, y = 0;
return a;
}
ll d = ex_gcd(b, a % b, y, x);
y -= a / b * x;
return d;
}
ll solve(ll a, ll b, ll t)
{
ll x, y, d, res;
d = ex_gcd(a, b, x, y);
if(t % d) return -1;
a /= d, b /= d, t /= d;
x *= t, y *= t;
res = (ll)1e18;
ll tmpx, tmpy, c = (y - x) / (a + b);
for(int i = c - 1; i <= c + 1; i++){
tmpx = x + i * b, tmpy = y - i * a;
if(tmpx * tmpy >= 0) res = min(res, max(abs(tmpx), abs(tmpy)));
else res = min(res, abs(tmpx) + abs(tmpy));
}
return res;
}
int main()
{
ll a, b, A, B;
scanf("%d", &T);
while(T--){
scanf("%lld%lld%lld%lld", &A, &B, &a, &b);
printf("%lld\n", solve(a, b, abs(B - A)));
}
return 0;