[Luogu P1495]曹冲养猪

时间:2023-03-10 03:01:10
[Luogu P1495]曹冲养猪

题目链接

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

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
#define ll long long
ll read(){
ll res=,f=;
char ch=getchar();
while(ch<''||ch>''){
if(ch=='-')f=-;
ch=getchar();
}
while(ch>=''&&ch<=''){
res=res*+(ch-'');
ch=getchar();
}
return res*f;
}
ll n,a[],b[],ans;
void exgcd(ll a,ll b,ll &x,ll &y){
if(b==)x=,y=;
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=,M[];
for(ll i=;i<=n;++i)Mk*=m[i];
for(ll i=;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<)ans+=Mk;
ans%=Mk;
}
int main(){
n=read();
for(int i=;i<=n;++i)a[i]=read(),b[i]=read();
intchina(a,b);
cout<<ans;
return ;
}