洛谷P4777 【模板】扩展中国剩余定理(EXCRT)

传送门

 

关于excrt

 1 //minamoto
 2 #include
 3 #include
 4 #define int long long
 5 using namespace std;
 6 #define getc() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
 7 char buf[1<<21],*p1=buf,*p2=buf;
 8 int read(){
 9     #define num ch-'0'
10     char ch;bool flag=0;int res;
11     while(!isdigit(ch=getc()))
12     (ch=='-')&&(flag=true);
13     for(res=num;isdigit(ch=getc());res=res*10+num);
14     (flag)&&(res=-res);
15     #undef num
16     return res;
17 }
18 const int N=1e5+5;
19 int n,ai[N],bi[N];
20 int mul(int a,int b,int mod){
21     int res=0;
22     while(b){
23         if(b&1) res=(res+a)%mod;
24         a=(a+a)%mod,b>>=1;
25     }
26     return res;
27 }
28 int exgcd(int a,int b,int &x,int &y){
29     if(b==0) return x=1,y=0,a;
30     int gcd=exgcd(b,a%b,x,y),t=x;
31     x=y,y=t-a/b*y;return gcd;
32 }
33 int excrt(){
34     int x,y,k,M=bi[1],ans=ai[1];
35     for(int i=2;i<=n;++i){
36         int a=M,b=bi[i],c=(ai[i]-ans%b+b)%b;
37         int gcd=exgcd(a,b,x,y),bg=b/gcd;
38         if(c%gcd!=0) return -1;
39         x=mul(x,c/gcd,bg);
40         ans+=x*M,M*=bg,ans=(ans%M+M)%M;
41     }
42     return (ans%M+M)%M;
43 }
44 signed main(){
45 //    freopen("testdata.in","r",stdin);
46     n=read();
47     for(int i=1;i<=n;++i) bi[i]=read(),ai[i]=read();
48     printf("%lld\n",excrt());
49     return 0;
50 }

 

转载于:https://www.cnblogs.com/bztMinamoto/p/9824646.html

你可能感兴趣的:(洛谷P4777 【模板】扩展中国剩余定理(EXCRT))