有这样一个问题:
{ x ≡ a 1 ( m o d m 1 ) x ≡ a 2 ( m o d m 2 ) … … x ≡ a n ( m o d m n ) \begin{cases} x\equiv a_1(mod~m_1)\\ x\equiv a_2(mod~m_2)\\ ……\\ x\equiv a_n(mod~m_n) \end{cases} ⎩⎪⎪⎪⎨⎪⎪⎪⎧x≡a1(mod m1)x≡a2(mod m2)……x≡an(mod mn)
其中,m两两互质,求满足所有同余方程的解。
#include
#define ll long long
using namespace std;
const int N=100;
int n,m[N],b[N];
ll M=1,ans;
ll exgcd(ll a,ll b,ll &x,ll &y){
if(b==0){
x=1,y=0;return a;
}
ll d=exgcd(b,a%b,x,y);
ll tmp=x;x=y;y=tmp-a/b*x;
return d;
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;++i){
scanf("%d%d",&m[i],&b[i]);
M*=m[i];
}
for(int i=1;i<=n;++i){
ll Mi,t,x,y;
Mi=M/m[i];
exgcd(Mi,m[i],x,y);
ans=(ans+1LL*x*Mi*b[i])%M;
}
cout<<(ans+M)%M<<endl;
return 0;
}
#include
#define ll long long
using namespace std;
const int N=1e5+10;
int n;ll m[N],a[N];
ll exgcd(ll a,ll b,ll &x,ll &y){
if(!b){
x=1;y=0;return a;
}
ll d=exgcd(b,a%b,x,y);
ll tmp=x;x=y;y=tmp-a/b*y;
return d;
}
ll mul(ll a,ll b,ll mod){
ll res=0;
for(;b;b>>=1){
if(b&1) res=(res+a)%mod;
a=(a+a)%mod;
}
return res;
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;++i) scanf("%lld%lld",&m[i],&a[i]);
ll k1,k2,m1,m2,a1,a2,c,d,x,y,x0;
m1=m[1],a1=a[1];
for(int i=2;i<=n;++i){
m2=m[i],a2=a[i];
c=a2-a1;c=(c%m[i]+m[i])%m[i];
d=exgcd(m1,m2,x,y);
if(c%d){
printf("-1\n");
return 0;
}
ll lc=m1/d*m2;
k1=(mul(x,c/d,m2)+m2)%m2;
x0=mul(k1,m1,lc)+a1;x0=(x0+lc)%(lc);
m1=lc;a1=x0;
}
cout<<x0<<endl;
return 0;
}
#include
#define ll long long
using namespace std;
const int N=1e5+10;
ll t,n,m,atk[N],p[N],a[N];
multiset<ll>s;
multiset<ll>::iterator it;
ll in(){
char ch=getchar();ll num=0,f=1;
while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
while(isdigit(ch)){num=num*10+(ch^48);ch=getchar();}
return num*f;
}
ll exgcd(ll a,ll b,ll &x,ll &y){
if(!b){x=1;y=0;return a;}
ll d=exgcd(b,a%b,x,y);
ll tmp=x;x=y;y=tmp-a/b*x;
return d;
}
ll mul(ll a,ll b,ll mod){
ll res=0;
for(;b;b>>=1){
if(b&1) res=(res+a)%mod;
a=(a+a)%mod;
}
return res;
}
int main(){
t=in();
E:while(t--){
n=in(),m=in();ll temp;
for(int i=1;i<=n;++i) a[i]=in();
for(int i=1;i<=n;++i) p[i]=in();
for(int i=1;i<=n;++i) atk[i]=in();
s.clear();
for(int i=1;i<=m;++i){temp=in();s.insert(temp);}
ll k,d,tmp,lcm,x,y,c1=0,m1=1,c,m,M=0;
for(int i=1;i<=n;++i){
it=s.upper_bound(a[i]);
if(it!=s.begin()) it--;
k=*it,s.erase(it);
s.insert(atk[i]);
M=max(M,(a[i]-1)/k+1);
k%=p[i];a[i]%=p[i];
if(!k&&!a[i]) continue;
if(!k&&a[i]){printf("-1\n");goto E;}
d=exgcd(k,p[i],x,y);
if(a[i]%d){printf("-1\n");goto E;}
m=p[i]/d;c=(mul((x%m+m)%m,a[i]/d,m)+m)%m;
d=exgcd(m1,m,x,y);tmp=c-c1;lcm=m1/d*m;tmp=(tmp+lcm)%lcm;
if(tmp%d){printf("-1\n");goto E;}
x=(mul(x,tmp/d,m/d)+m/d)%(m/d);
c1=(mul(m1,x,lcm)+c1)%lcm;m1=lcm;
//m1=m1/d*m;
//c1=(c1+mul(mul(m1/m,((c-c1)%m1+m1)%m1,m1),(x%m1+m1)%m1,m1))%m1;
}
printf("%lld\n",c1>=M?c1:c1+m1*((M-c1-1)/m1+1));
}
return 0;
}