ZOJ 2593 One Person Game(扩展欧几里德、|x| + |y|最小)

题目链接:
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;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值