题目:
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 A, B, a and b, separated by spaces. (-231 ≤ A, B < 231, 0 < a, b < 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
代码如下:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll ans;
ll exgcd(ll a,ll b,ll &x,ll &y)
{
if(!b){
x = 1;
y = 0;
return a;
}
ans = exgcd(b,a % b,x,y);
ll temp = x;
x = y;
y = temp - (a / b) * y;
return ans;
}
ll china(ll a,ll b,ll c)
{
ll x,y,am,bm,sum;
exgcd(a,b,x,y);
if(c % ans) return -1;//方程无解
am = a / ans;
bm = b / ans;
x = x * (c / ans);
y = y * (c / ans);
sum = fabs(x) + fabs(y);
for(int i = -x / bm - 1;i <= -x / bm + 1;i++){
ll X = x + i * bm;
ll Y = y - i * am;
ll ans = fabs(X) + fabs(Y);
if(ans < sum) sum = ans;
}
for(int i = y / am - 1;i <= y / am + 1;i++){
ll X = x + i * bm;
ll Y = y - i * am;
ll ans = fabs(X) + fabs(Y);
if(ans < sum) sum = ans;
}
return sum;
}
int main()
{
int t;
ll A,B,a,b,x,y,c,C;
cin >> t;
while(t--){
cin >> A >> B >> a >> b;
c = a + b;
C = fabs(A - B);
ll t1 = china(a,b,C);
ll t2 = china(a,c,C);
ll t3 = china(b,c,C);
if(t1 == -1 && t2 == -1 && t3 == -1){
cout << "-1" << endl;
continue;
}
ans = t2;
if(t1 < t2) ans = t1;
if(ans > t3) ans = t3;
cout << ans << endl;
}
return 0;
}
题意:
给你A,B两点坐标,从A点出发,可以走a,b,a + b,问你是否可以到达B点,不可以输出-1,可以输出最小步数。
思路:
那么根据题意你可以得到方程:ax +by + cz = C,其中C = fabs(A - B)
然后把这个方程拆成三个方程组:ax + by = C ax + cy = C bx + cy = C(这里c = a + b),现在相当于要求|x| +|y|的最小值。
那我们现在就分别对这三个方程进行求解,假设要求方程:ax +by = 1的解,我们使用扩展欧几里得算法求出一组解x,y。
那么方程ax + by = C时且满足C % gcd(a,b) = 0 的解x0,y0可以表示为:
x0 = x * (C / gcd(a,b))
y0 = y * (C / gcd(a,b))
我们知道方程ax + by = C的通解是x = x0 + t1 * (b / gcd(a,b)) y = y0 + t2* (a / gcd(a,b))
这里让am = a / gcd(a,b) bm = b / gcd(a,b)。
由图像|x| + |y| = c平移可以看出:考虑范围 [-x0 / bm - 1, -x0 / bm + 1] [y0 / am - 1, y0 / am + 1]就可以得出最大值。