曹冲养猪

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

【题解】

很裸的中国剩余定理,不能再裸了。。。(注意用long long)

 1 /*************
 2   Vijos 1164
 3   by chty
 4   2016.11.1
 5 *************/
 6 #include<iostream>
 7 #include<cstdio>
 8 #include<cstring>
 9 #include<cstdlib>
10 #include<ctime>
11 #include<cmath>
12 #include<algorithm>
13 using namespace std;
14 typedef long long ll;
15 ll n,ans,M(1),a[15],m[15];
16 inline ll read()
17 {
18     ll x=0,f=1;  char ch=getchar();
19     while(!isdigit(ch))  {if(ch=='-')  f=-1;  ch=getchar();}
20     while(isdigit(ch))  {x=x*10+ch-'0';  ch=getchar();}
21     return x*f;
22 }
23 void exgcd(ll a,ll b,ll &x,ll &y)
24 {
25     if(b==0) {x=1; y=0; return;}
26     exgcd(b,a%b,x,y);
27     ll t=x;x=y;y=t-a/b*y;
28 }
29 int main()
30 {
31     //freopen("cin.in","r",stdin);
32     //freopen("cout.out","w",stdout);
33     n=read();
34     for(ll i=1;i<=n;i++)  m[i]=read(),a[i]=read(),M*=m[i];
35     for(ll i=1;i<=n;i++)
36     {
37         ll x,y,Mi=M/m[i];
38         exgcd(Mi,m[i],x,y);
39         ans=(ans+Mi*x*a[i])%M;
40     }
41     if(ans<0)  ans+=M;
42     printf("%I64d
",ans);
43     return 0;
44 }
原文地址:https://www.cnblogs.com/chty/p/6020216.html