PC/UVa:110707/10090
- 这道题的数据如果用
int
或者long
可能会溢出,所以要使用long long
- 第一次超时,是因为在把
x
和y
修正为正数时采用的是一次一次变化的方法,而不是一次乘法直接变为正数 - 后面超时,是因为又去一次一次的变化
x
和y
去算最小值,这样算起来非常慢,而没法发现这是一个线性函数,极值就在区间端点上
#include <iostream>
using namespace std;
long long GCD(long long a, long long b, long long &x, long long &y)
{
if (a < b) return GCD(b, a, y, x);
if (b == 0){
x = 1;
y = 0;
return a;
}
long long g = GCD(b, a % b, x, y), tmp;
tmp = y;
y = x - a / b * y;
x = tmp;
return g;
}
int main()
{
long long n = 0, c1 = 0, c2 = 0, n1 = 0, n2 = 0;
while (cin >> n){
if (n == 0) break;
cin >> c1 >> n1 >> c2 >> n2;
long long x, y;
long long g = GCD(n1, n2, x, y);
long long lcm = n1 / g * n2;
long long m1 = lcm / n1, m2 = lcm / n2, multiple;
if (n % g == 0){
/*
n1 * x + n2 * y = gcd(n1, n2)
x增加m1 = lcm(n1, n2) / n1, y同时减少m2 = lcm(n1, n2) / n2
或者x减少,y增加,等式仍然成立
*/
//先将x,y修正为正数
x *= n / g;
y *= n / g;
if (x <= 0){
multiple = (-x + m1 - 1) / m1;
x += multiple * m1;
y -= multiple * m2;
}
else{
multiple = (-y + m2 - 1) / m2;
x -= multiple * m1;
y += multiple * m2;
}
if (x < 0 || y < 0){
cout << "failed" << endl;
}
else{
if (c1 * m1 > c2 * m2){
//此时y取最大值,x取最小值时花费最小
multiple = x / m1;
x -= multiple * m1;
y += multiple * m2;
cout << x << ' ' << y << endl;
}
else{
//此时n1取最大值,n2取最小值时花费最小
multiple = y / m2;
x += multiple * m1;
y -= multiple * m2;
cout << x << ' ' << y << endl;
}
}
}
else{
cout << "failed" << endl;
}
}
return 0;
}
/*
43
1 3
2 4
40
5 9
5 12
0
*/