Description
给定若干个形如$x\equiv a_i \pmod {m_i}$的同余方程,其中m两两互质,求x
Solution
这是中国剩余定理的模板题,具体解法如下:
我们首先求出$M=\prod\limits_{i=1}^{n}{m_i}$
那么令$M_i=\frac{M}{m_i}$
然后令$t_i=M_i^{-1} \pmod {m_i}$
最后令$s_i=t_iM_i$
我们只要求出$x\equiv \sum\limits_{i=1}^{n}{a_is_i}\pmod M$即可
逆元可以用Exgcd求解,时间复杂度为O(nlogn)
Code
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 inline int read() { 5 int ret = 0, op = 1; 6 char c = getchar(); 7 while (!isdigit(c)) { 8 if (c == '-') op = -1; 9 c = getchar(); 10 } 11 while (isdigit(c)) { 12 ret = ret * 10 + c - '0'; 13 c = getchar(); 14 } 15 return ret * op; 16 } 17 ll exgcd(ll a, ll b, ll &x, ll &y) { 18 if (!b) { 19 x = 1, y = 0; 20 return a; 21 } 22 ll gcd = exgcd(b, a % b, x, y); 23 ll x2 = x, y2 = y; 24 x = y2; 25 y = x2 - (a / b) * y2; 26 return gcd; 27 } 28 ll n, a[12], b[12], mod = 1; 29 ll ans; 30 int main() { 31 n = read(); 32 for (register int i = 1; i <= n; ++i) { 33 a[i] = read(), b[i] = read(); 34 mod *= a[i]; 35 } 36 for (register int i = 1; i <= n; ++i) { 37 ll m = mod / a[i]; 38 ll x = 0, y = 0; 39 exgcd(m, a[i], x, y); 40 ans = (ans + (x * m * b[i]) % mod + mod) % mod; 41 } 42 printf("%lld\n", ans); 43 return 0; 44 }