您的位置:首页 > 其它

POJ 2142 扩展欧几里得

2017-03-11 10:56 459 查看

题解

扩欧求可行解x, y

分别取对于a, b参数的最小非负整数解情况, 求|x| + |y|最小

如果2中两种情况绝对值之和相同进一步找最小a|x| + b|y|

code

#include <iostream>
using namespace std;
typedef long long ll;

int a, b, c, x, y;

int extend_gcd(int a, int b, int &x, int &y){
if(b == 0){
x = 1;
y = 0;
return a;
}

int d = extend_gcd(b, a % b, y, x);
y -= a / b * x;
return d;
}

inline int Abs(int x) { return x >= 0 ? x : -x;}

int main(){

while(cin >> a >> b >> c, a + b + c){
int d = extend_gcd(a, b, x, y);
if(c % d){
cout << "no solution" << endl;
continue;
}
x *= c / d, y *= c / d;
int x1 = (x % (b / d) + b / d) % (b / d);
int y1 = Abs((c - a * x1) / b);
int y2 = (y % (a / d) + a / d) % (a / d);
int x2 = Abs((c - b * y2) / a);
if(x1 + y1 < x2 + y2)
cout << x1 << " " << y1 << endl;
else{
if(x1 + y1 > x2 + y2)
cout << x2 << " " << y2 << endl;
else{
if(a * x1 + b * y1 <= a * x2 + b * y2) cout << x1 << " " << y1 << endl;
else cout << x2 << " " << y2 << endl;
}
}
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息