巴蜀1738 曹冲养猪

Description

  自从曹冲搞定了大象以后,曹操就开始捉摸让儿子干些事业,于是派他到中原养猪场养猪,可是曹冲满不高兴,于是在工作中马马虎虎,有一次曹操想知道母猪的数量,于是曹冲想狠狠耍曹操一把。举个例子,假如有16头母猪,如果建了3个猪圈,剩下1头猪就没有地方安家了。如果建造了5个猪圈,但是仍然有1头猪没有地方去,然后如果建造了7个猪圈,还有2头没有地方去。你作为曹总的私人秘书理所当然要将准确的猪数报给曹总,你该怎么办? 

Input

  第一行包含一个整数n (n <= 10) – 建立猪圈的次数,接下来n行,每行两个整数ai, bi( bi <= ai <= 1000), 表示建立了ai个猪圈,有bi头猪没有去处。你可以假定ai,aj互质.

Output

  输出包含一个正整数,即为曹冲至少养母猪的数目。

Sample Input

3 3 1 5 1 7 2

Sample Output

16

Source

xinyue

中国剩余定理。

读入优化比scanf慢了4ms,迷

 1 /*by SilverN*/
 2 #include<algorithm>
 3 #include<iostream>
 4 #include<cstring>
 5 #include<cstdio>
 6 #include<cmath>
 7 #define LL long long
 8 using namespace std;
 9 const int mxn=15;
10 LL a[mxn],b[mxn];
11 int n;
12 LL exgcd(LL a,LL b,LL &x,LL &y){
13     if(!b){
14         x=1;y=0;
15         return a;
16     }
17     LL res=exgcd(b,a%b,x,y);
18     LL t=x;x=y;y=t-a/b*x;
19     return res;
20 }
21 LL clc(){
22     LL M=1;
23     LL res=0;
24     int i,j;LL x,y;
25     for(i=1;i<=n;i++){M*=a[i];}
26     for(i=1;i<=n;i++){
27         LL tmp=M/a[i];
28         exgcd(tmp,a[i],x,y);
29         res=(res+tmp*x*b[i])%M;
30     }
31     res=(res+M)%M;
32     return res;
33 }
34 int main(){
35     scanf("%d",&n);
36     int i,j;
37     for(i=1;i<=n;i++){
38         scanf("%d%d",&a[i],&b[i]);
39     }
40     LL ans=clc();
41     printf("%lld
",ans);
42     return 0;
43 }
原文地址:https://www.cnblogs.com/SilverNebula/p/5913213.html