https://ac.nowcoder.com/acm/contest/4853/D
已知a b c k 求出x y z。
考虑ax+by+cz=k,那么我们移项得ax+by=k-cz,如果k在剪掉cz之后依然存在解。
那么gcd(a,b)∣k-cz。
设g=gcd(a,b)那么现在就是求Tg+cz=k的解,
并且要保证z尽量小。我们做一次exgcd就行了。
接下来就是求ax+by=k-cz的非负解,再做一次exgcd就行了。
如果要保证做法正确的话,需要用a,b,c分别作为第三个数去求解。
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstring>
using namespace std;
typedef long long ll;
int gcd(int a, int b) {
return b ? gcd(b, a % b) : a;
}
int exgcd(int a,int b,ll &x,ll &y)
{
if(!b)
{
x=1;
y=0;
return a;
}
int r=exgcd(b,a%b,y,x);
y-=a/b*x;
return r;
}
int a, b, c;
ll k, x, y;
ll resx, resy, resz;
bool solve(int a, int b, int c, ll k) {
ll d = gcd(a, b);
ll r = exgcd(d, c, x, y);
y *= k / r;
y=(y%(d/r)+d/r)%(d/r);//求出z的最小值
resz = y;
k -= c * y;
d = exgcd(a, b, x, y);
x*=k/d;
x=(x%(b/d)+b/d)%(b/d);//求出x的最小值
y=(k-a*x)/b;
resx = x, resy = y;
if (resx >= 0 && resy >= 0 && resz >= 0)return true;
return false;
}
int main()
{
scanf("%d %d %d %lld", &a, &b, &c, &k);
if (solve(a, b, c, k)) {
printf("%lld %lld %lld\n", resx, resy, resz);
return 0;
}
if (solve(a, c, b, k)) {
printf("%lld %lld %lld\n", resx, resz, resy);
return 0;
}
if (solve(b, c, a, k)) {
printf("%lld %lld %lld\n", resz, resx, resy);
return 0;
}
return 0;
}