P3868 [TJOI2009]猜数字

[TJOI2009]猜数字

中国剩余定理

求解i=1 to n : x≡a[i] (mod b[i])的同余方程组

设 t= ∏i=1 to n b[i]

我们先求出 i=1 to n : x≡1 (mod b[i]) ; j=1 to n,j≠i : x≡0 (mod b[j])的解

我们可以 把 t/b[i] y 代入 x 求解

ans= ∑i=1 to n : x[i]a[i]

中间过程可能爆long long所以用快速乘

(当然模数不互质的话就只能excrt了)

#include<iostream>
#include<cctype>
using namespace std;
typedef long long ll;
ll n,A[12],B[12],lcm,t=1,X,Y,ans,m;
inline ll kmul(ll x,ll y){ //快速乘
    ll tmp=x*y-(ll)((long double)x/t*y+1.0e-8)*t;
    return tmp>0 ? tmp:tmp+t;
}
void exgcd(ll a,ll b,ll &x,ll &y){
    if(!b) x=1,y=0;
    else exgcd(b,a%b,y,x),y-=x*(a/b);
}
int main(){
    cin>>n;
    for(int i=1;i<=n;++i) cin>>A[i];
    for(int i=1;i<=n;++i) cin>>B[i],t*=B[i];
    for(int i=1;i<=n;++i){
        exgcd(B[i],m=t/B[i],X,Y);
        ans=(ans+kmul(kmul(m,Y),A[i])%t+t)%t;
    }cout<<ans;
}
原文地址:https://www.cnblogs.com/kafuuchino/p/9772530.html