同余方程组(EXCRT)(luogu4777)
Posted lizitong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了同余方程组(EXCRT)(luogu4777)相关的知识,希望对你有一定的参考价值。
#include<cstdio>
#include<algorithm>
#define ll long long
using namespace std;
ll k;
ll a1,r1;
ll a2,r2;
ll x,y;
ll g;
void init()
{
scanf("%lld",&k);
}
void exgcd(ll a,ll b)
{
if(b==0)
{
x = 1;
y = 0;
}else
{
exgcd(b,a%b);
ll t = x;
x = y;
y = t-a/b*x;
}
}
void gcd(ll x,ll y)
{
if(y==0)
{
g = x;
return ;
}
gcd(y,x%y);
}
ll ksc(ll x,ll y,ll mod)
{
ll ans = 0,kk=1;
if(x<0)x=-x,kk=-kk;
if(y<0)y=-y,kk=-kk;
while(y)
{
if(y%2)
{
ans = (ans+x)%mod;
}
y>>=1;
x = (x+x)%mod;
}
return ans%mod*kk;
}
void solve()
{
scanf("%lld%lld%lld%lld",&a1,&r1,&a2,&r2);
ll a,b,c;
a = a1;
b = a2;
c = r2-r1;//ax=c(mod b)
gcd(a,b);
if(c%g!=0)
{
printf("-1
");
return ;
}
a = a/g;
b = b/g;
c = c/g;
exgcd(a,b);
x = (ksc(x,c,b)+b)%b;//x = k0
c = x*a1+r1;
gcd(a1,a2);
b = a1/g*a2;
k = k-2;
r1 = c;
a1 = b;
while(k--)
{
scanf("%lld%lld",&a2,&r2);
ll a,b,c;
a = a1;
b = a2;
c = r2-r1;//ax=c(mod b)
gcd(a,b);
if(c%g!=0)
{
printf("-1
");
return ;
}
a = a/g;
b = b/g;
c = c/g;
exgcd(a,b);
x =(ksc(x,c,b)+b)%b;//x = k0
c = x*a1+r1;
gcd(a1,a2);
b = a1/g*a2;
r1 = c;
a1 = b;
}
exgcd(1,a1);
x = (ksc(x,r1,a1)+a1)%a1;
printf("%lld
",x);
}
int main()
{
init();
solve();
return 0;
}
以上是关于同余方程组(EXCRT)(luogu4777)的主要内容,如果未能解决你的问题,请参考以下文章
EXCRT模板POJ2891/LuoGu4777Strange Way to Express Integers拓展中国剩余定理