题目大意:
就是现在给出3个整数 a , b , c
其中 a <= b <= c , a, b 在int 范围内, c 在 long long 的范围内
问是否存在非负整数 x ,y 使得 a*x + b*y = c 成立, 若存在则输出 x + y 最小的那一组 x, y
大致思路:
首先需要知道扩展欧几里得算法可以求出使得 a*x + b*y = gcd(a, b)成立的一个解 x0, y0
并且有这样的一个结论:
对于整数c, 如果c 是 gcd(a, b)的倍数, 则a*x + b*y = c 有解,比如 x0*(c / gcd(a,b) , y0*(c / gcd(a, b))
如果c不是gcd(a, b) 的倍数, 则a*x + b*y = c无解
那么使用扩展欧几里得算法求出了一个解 x0, y0 之后也算出了gcd(a,b)可以先判断一下c是否是gcd(a, b) 的倍数,之后由于欧几里得算法得到的这个解 x0, y0 不保证其都是非负数,那么为了调整解, 由于输入的 a,b,c是递增的, 可以发现x0要最小才能x + y 最小, 也就是说要找到最接近于零的那个非负数x
由于a*x0 + b*y0 = gcd(a,b)所以对于 a*x0 + b*y0 = c来说其解为:
x0*(c / gcd(a, b)) y0*(c / gcd(a, b))
现在有这样一种调整的方法:
由于x1, x2是方程a*x1 + b*x2 = c 的解, 不难发现 a*(x1 + b) - b*(y1 - a) = c也成立,也就是说 x1 + k*b , y1 - k*a也是其解
那么久可以调整得到的解使得x最接近零且不为负也就是对于调整至正数之后对b取模即可
这里还有一个问题就是要防止溢出,在下面的代码中也用到了一点处理
这道题最后就是注意一下输出格式问题吧。
代码如下:
Result : Accepted Memory : 0 KB Time 6 ms
/*
* Author: Gatevin
* Created Time: 2014/8/2 20:05:11
* File Name: test.cpp
*/
#include<iostream>
#include<sstream>
#include<fstream>
#include<vector>
#include<list>
#include<deque>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cctype>
#include<cmath>
#include<ctime>
#include<iomanip>
using namespace std;
const double eps(1e-8);
typedef long long lint;
lint a,b,c;
lint Ex_gcd(lint a, lint b, lint& x, lint& y)
{
if(b == 0)
{
x = 1, y = 0;
return a;
}
else
{
lint r = Ex_gcd(b, a % b, y, x);
y -= x*(a / b);
return r;
}
}
int main()
{
while(cin>>a>>b>>c, a + b + c)
{
lint x, y;
lint g = Ex_gcd(a, b, x, y);
if(c % g)
{
cout<<"Unquibable!"<<endl;
continue;
}
if(x < 0)
{
lint tmp = - (x / b);
x += tmp*b + b;
}
a /= g;//防止数据溢出
b /= g;
c /= g;
x = ( ((x % b)*(c % b)) % b );//取模范围之前处理之后变小了
y = (c - a*x) / b;
if(y < 0)
{
cout<<"Unquibable!"<<endl;
}
else
{
if(x == 1)
{
cout<<"1 foom and ";
}
else
{
cout<<x<<" fooms and ";
}
if(y == 1)
{
cout<<y<<" foob for a twob!"<<endl;
}
else
{
cout<<y<<" foobs for a twob!"<<endl;
}
}
}
return 0;
}