Codevs 3990 [中国剩余定理]

模板题

注意如何得到[a,b]区间范围内的解

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long ll;
const int N=15;
inline ll read(){
    char c=getchar();ll x=0,f=1;
    while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
    while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
    return x*f;
}
ll n,l,r;
ll m[N],a[N],M=1;
void exgcd(ll a,ll b,ll &d,ll &x,ll &y){
    if(b==0) d=a,x=1,y=0;
    else exgcd(b,a%b,d,y,x),y-=(a/b)*x;
}
ll Inv(ll a,ll p){
    ll d,x,y;
    exgcd(a,p,d,x,y);
    return d==1?(x+p)%p:-1;
}
ll CRT(int n,ll *a,ll *m){
    ll x=0;
    for(int i=1;i<=n;i++){
        ll w=M/m[i];
        x=(x+a[i]*w%M*Inv(w,m[i]))%M;
    }
    return x;
}
int main(){
    freopen("in","r",stdin);
    n=read();l=read();r=read();
    for(int i=1;i<=n;i++) m[i]=read(),M*=m[i],a[i]=read();
    ll x=CRT(n,a,m),sum=0,mn=0;
    //printf("M %lld %lld\n",x,M);

    if(x<l) x*=(l-x-1)/x+1 +1;//,printf("x %lld\n",x);
    if(x<=r) sum=(r-x)/M+1,mn=x;
    printf("%lld\n%lld",sum,mn);
}

 

posted @ 2017-02-14 19:08  Candy?  阅读(226)  评论(0编辑  收藏  举报