[lnsyoj163/luoguP1495]曹冲养猪

题意

求线性同余方程组

{xb1(moda1)xb2(moda2)xbn(modan)

的最小非负整数解,保证 a1,a2,,an互质。

sol

求解线性同余方程组,我们通常会选择中国剩余定理(CRT)来解决。
我们计算 A=a1a2anmi=Aai,由于 mi 是除 aia 中所有数的倍数,因此 kmi0(modap)(pi),即该值只对第 i 个线性同余方程有影响。因此,我们只需要解线性同余方程mix1(modai),那么bix就是第i个线性同余方程的贡献,贡献的和即为线性同余方程组的一组合法解,将其取模A即可求出最小合法解

代码

#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;
typedef long long LL;

const int N = 15;

int n;
int a[N], b[N];

LL exgcd(LL a, LL b, int &x, int &y){
    if (!b){
        x = 1, y = 0;
        return a;
    }
    LL d = exgcd(b, a % b, y, x);
    y -= a / b * x;
    return d;
}

int main(){
    cin >> n;
    for (int i = 1; i <= n; i ++ ) cin >> a[i] >> b[i];
    LL M = 1;
    for (int i = 1; i <= n; i ++ ) M *= a[i];
    LL sum = 0;
    for (int i = 1; i <= n; i ++ ) {
        int x, y;
        LL d = exgcd(M / a[i], (LL) a[i], x, y);
        int t = abs(a[i] / d);
        x /= d;
        sum += (x % t + t) % t * (M / a[i]) * b[i];
    }

    cout << sum % M << endl;

    return 0;
}
posted @   是一只小蒟蒻呀  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示