曹冲养猪acwing(中国剩余定理)

题目:https://www.acwing.com/problem/content/1300/
题意:中国剩余定理
x = b1 (mod a1)
x = b2 (mod a2)
x = b3 (mod a3)

x = bi (mod ai)

求最小的满足x的解

解析:中国剩余定理: M是所有ai的乘积, mi是M / ai(出自己之外的所有数的乘积)
ti是关于ai的逆元。 则答案 = SUM(bi * ti * mi);
上边的就是:ti * mi 恒等于 1 (mod ai) ⇒ ti * mi + ai * x = 1 (用扩展欧几里得求 解)

不大很懂逆元咋求得:https://blog.csdn.net/destiny1507/article/details/81751168大佬的

在这里插入图片描述

代码:

#include <bits/stdc++.h>
#define lowbit(x) x&(-x)
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const int N = 1e7 + 20;

int a[12], b[12];
inline void Ex_gcd(ll a, ll b, ll &x, ll &y)
{
    
    
    if (b == 0) x = 1, y = 0;
    else {
    
    
        Ex_gcd(b, a % b, y, x);
        y -= a / b * x;
    }
}

int main()
{
    
    
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);

    ll M = 1;

    int n; cin >> n;
    for (int i = 1; i <= n; i++) cin >> a[i] >> b[i], M *= a[i];

    ll ans = 0;
    for (int i = 1; i <= n; i++) {
    
    
        ll mi = M / a[i];
        ll ti, x;
        Ex_gcd(mi, a[i], ti, x);

        ans += b[i] * mi * ti;
    }

    cout << (ans % M + M) % M << endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/YingShen_xyz/article/details/112918383