• 51nod--1079 中国剩余定理


    题目:

    1079 中国剩余定理
    基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题 收藏 关注
    一个正整数K,给出K Mod 一些质数的结果,求符合条件的最小的K。例如,K % 2 = 1, K % 3 = 2, K % 5 = 3。符合条件的最小的K = 23。
    Input
    第1行:1个数N表示后面输入的质数及模的数量。(2 <= N <= 10)
    第2 - N + 1行,每行2个数P和M,中间用空格分隔,P是质数,M是K % P的结果。(2 <= P <= 100, 0 <= K < P)
    Output
    输出符合条件的最小的K。数据中所有K均小于10^9。
    Input示例
    3
    2 1
    3 2
    5 3
    Output示例
    23

    分析:

    若 m1, m2, m3…mi 是两两互素的正整数, 则同余方程组:
    x = a1 (mod m1)
    x = a2 (mod m2)

    x = an (mod mn)
    有模 M = m1 * m2 * m3 * m4 … mn 的唯一解。
    令 Mi = M / mi;
    易得 (Mi, mi) = 1 , 所以有 MiPi = 1(mod mi)
    则 方程组的解 x=ni=1ai*Mi*Pi

    实现:

    #include <bits/stdc++.h>
    
    using namespace std;
    
    typedef long long LL;
    
    const int maxn = 100;
    
    LL a[maxn], m[maxn];
    
    void Exgcd(LL a, LL b, LL& d, LL& x, LL& y) {
        if(b == 0) { d = a, x = 1, y = 0; }
        else {
            Exgcd(b, a%b, d, y, x);
            y -= x * (a/b);
        }
    }
    
    LL China(int n, LL* a, LL* m) {
        LL M = 1, d, y, x = 0;
        for(int i = 0; i < n; ++i) M *= m[i];
        for(int i = 0; i < n; ++i) {
            LL w = M / m[i];
            Exgcd(m[i], w, d, d, y);
            x = (x + y*w*a[i]) % M;
        }
        return (x + M) % M;
    }
    
    int main() {
        int n;
        while(cin >> n) {
            for(int i = 0; i < n; ++i) {
                cin >> m[i] >> a[i];
            }
            cout << China(n, a, m) <<endl;
        }
    }
    
  • 相关阅读:
    MySQL、Redis 和 MongoDB 的优缺点
    解决数据库高并发
    数据库事务
    Mysql 数据库存储的原理?
    CSRF
    MVC模型和MVT模型
    AJAX
    正则表达式-re模块
    ddt-数据驱动测试
    python-时间格式化
  • 原文地址:https://www.cnblogs.com/aoxuets/p/5506837.html
Copyright © 2020-2023  润新知