P1495 [template] Chinese Remainder Theorem (CRT) / Cao Chong pig

Title Description
 

Since Cao Chong to get the elephant after Cao Cao began to fathom her son to do some business, then sent him to the Central Plains pig farms, but Cao Chong full of happy, so so-so at work, once Cao Cao wanted to know the number of sows , so Cao Cao Chong would like to play a fiercely. For example, if there are 16 sows, if built three pigsty, there is no place to rest one pig settled down. If built five pigsty, but there are still a pig no place to go, and then if the construction of seven pigsty, there are two no place to go. You give Cao, how can you do as a private secretary general Cao of course you want to accurately report the number of pigs?

Input Format
 

The first row contains an integer n (n <= 10) - to establish the number of the pigsty, the solution down n lines of two integers ai, bi (bi <= ai <= 1000), ai represents the establishment of a pigsty there is no place for bi pigs. You can assume that ai, aj relatively prime.

Output Format

Output includes a positive integer, i.e. the number of sows to raise at least Cao Chong.




For linear congruence equation x≡a I (m MOD I ) (I = n-.... 1)

If m I pairwise quality, the x in mod M must be a solution, at M = m . 1 m 2 m . 3 ... m n-

 

Construction process solutions for:

Ling M i = M / m i

Obviously (M I , m I ) =. 1, so that M I modulo m I inverse element is present, this inverse element provided as T I

Then there are M I T I ≡1 (m MOD I ), M I T I ≡1 (MOD m J ) (J ≠ I)

Further in A I M I T I ≡1 (m MOD I ), A I M I T I ≡1 (MOD m J ) (J ≠ I)

Accordingly solution is X = A . 1 M . 1 T . 1  + A 2 M 2 T 2 + ... + A n- M n- T n-

 

exgcd inversion yuan:

Exgcd role is the solution ax + by = gcd (a, b),

Order A M = I  , B = m I , because they are relatively prime, so the equation is converted to M I X m + I Y. 1 =

Obviously resulting solution x satisfy M I x≡1 (m MOD I ) .

 1 #include<bits/stdc++.h>
 2 #define ll long long
 3 using namespace std;
 4 ll n,a[1003],m[1003]; 
 5 void exgcd(ll a,ll b,ll &x,ll &y){
 6     if(b==0){
 7         x=1,y=0;
 8         return;
 9     }
10     //a=bq+r 
11     ll q=a/b,r=a%b;
12     exgcd(b,r,y,x);
13     y -= q*x;
14 }
15 ll inv(ll a,ll b){
16     ll x,y;
17     exgcd(a,b,x,y);
18     return x;
19 } 
20 ll CRT(){
21     ll M=0,ret=0;
22     for(int i=1;i<=n;++i)M*=m[i];
23     for(int i=1;i<=n;++i){
24         ll Mi=M/m[i],ti=inv(Mi,m[i]);
25         ret=(ret+a[i]*Mi*ti)%M;
26     }
27     return ret;
28 }
29 int main(){
30     cin>>n;
31     for(int i=1;i<=n;++i)
32       cin>>a[i]>>m[i];
33   cout<<CRT();
34 } 
View Code

 

 

Guess you like

Origin www.cnblogs.com/vv123/p/12329533.html