[Luogu P1495]曹冲养猪

题目链接

中国剩余定理(孙子定理)的裸题。直接放代码。

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
#define ll long long
ll read(){
    ll res=0,f=1;
    char ch=getchar();
    while(ch<'0'||ch>'9'){
        if(ch=='-')f=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9'){
        res=res*10+(ch-'0');
        ch=getchar();
    }
    return res*f;
}
ll n,a[15],b[15],ans;
void exgcd(ll a,ll b,ll &x,ll &y){
    if(b==0)x=1,y=0;
    else{
        exgcd(b,a%b,x,y);
        ll xt=x;
        x=y;
        y=xt-a/b*y;
    }
}
void intchina(ll *m,ll *u){
    ll Mk=1,M[15];
    for(ll i=1;i<=n;++i)Mk*=m[i];
    for(ll i=1;i<=n;++i){
        M[i]=Mk/m[i];
        ll x,y;
        exgcd(M[i],m[i],x,y);
        ans=(ans%Mk+M[i]*x*u[i]%Mk+Mk)%Mk;
    }
    while(ans<0)ans+=Mk;
    ans%=Mk;
}
int main(){
n=read();
for(int i=1;i<=n;++i)a[i]=read(),b[i]=read();
intchina(a,b);
cout<<ans;
return 0;
}
原文地址:https://www.cnblogs.com/clockwhite/p/10718311.html