zoukankan      html  css  js  c++  java
  • 【洛谷P1495】曹冲养猪

    Description

    给定若干个形如$xequiv a_i pmod {m_i}$的同余方程,其中m两两互质,求x

    Solution

    这是中国剩余定理的模板题,具体解法如下:

    我们首先求出$M=prodlimits_{i=1}^{n}{m_i}$

    那么令$M_i=frac{M}{m_i}$

    然后令$t_i=M_i^{-1} pmod {m_i}$

    最后令$s_i=t_iM_i$

    我们只要求出$xequiv sumlimits_{i=1}^{n}{a_is_i}pmod M$即可

    逆元可以用Exgcd求解,时间复杂度为O(nlogn)

    Code

     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
    ", ans);
    43     return 0;
    44 }
    AC Code
  • 相关阅读:
    ASP.NET MVC 学习之路-2
    ASP.NET MVC 学习之路-1
    mvp框架
    Linq基础
    C# Lambda表达式
    三层架构基础
    Protobuf-net基础
    AutoResetEvent和ManualResetEvent
    解题报告——POJ 2299
    解题报告——POJ 2726
  • 原文地址:https://www.cnblogs.com/shl-blog/p/11283410.html
Copyright © 2011-2022 走看看