Generally Chinese Remainder Theorem

http://poj.org/problem?id=2891

The meaning of problems: Group given k: MOD (divisor), a (remainder) satisfy the requirements of x.

Solution: Two two-equation merger.

https://blog.csdn.net/qq_34446253/article/details/52192786

//#include <bits/stdc++.h>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <stdio.h>
#include <queue>
#include <stack>;
#include <map>
#include <set>
#include <ctype.h>
#include <string.h>
#include <vector>
#define ME(x , y) memset(x , y , sizeof(x))
#define SF(n) scanf("%d" , &n)
#define rep(i , n) for(int i = 0 ; i < n ; i ++)
#define INF  0x3f3f3f3f
#define mod 1000000007
#define PI acos(-1)
using namespace std;
typedef long long ll ;
ll ad[100009] , m[100009];
ll d , x , y ;

void gcd(ll a , ll b , ll &d , ll &x , ll &y)
{
    if(b == 0)
    {
        x = 1 ;
        y = 0 ;
        d = a ;
    }
    else{
        gcd(b , a%b , d , x , y);
        ll t = x ;
        x = y ;
        y = t - (a/b)*y;
    }
}

ll CRTx(ll n)
{
    ll a1 = ad[0] , n1 = m[0] , a2 , n2;
    for(int i = 1 ; i < n ; i++)
    {
        a2 = ad[i] , n2 = m[i];
        gcd(n1 , n2 , d , x , y);
        if((a1-a2) % d) return -1 ;
        ll lcm = n1 * n2 / d ;
        ll u0 = ((x * (a1-a2)/d) % (n2/d) + (n2/d))%(n2/d);
        a1 = (a1 - u0*n1) % lcm ;
        n1 = lcm ;
    }
    return (a1 % n1 + n1) % n1 ;
}

int main()
{
    /*#ifdef ONLINE_JUDGE
    #else
        freopen("D:/c++/in.txt", "r", stdin);
        freopen("D:/c++/out.txt", "w", stdout);
    #endif*/
    ll n ;
    while(~scanf("%lld" , &n))
    {
        for(int i = 0 ; i < n ; i++)
        {
            scanf("%lld%lld" , &m[i] , &ad[i]);
        }
        cout << CRTx(n) << endl ;
    }

    return 0 ;
}

Guess you like

Origin www.cnblogs.com/nonames/p/12153604.html