斩杀线计算大师 三元一次方程解

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值