中国剩余定理的裸题,不过所给的余数时非互质的。
#include <iostream>
#include <stdio.h>
#define LL long long
#define maxn 100050
using namespace std;
LL m[maxn];
LL a[maxn];
LL exgcd(LL a,LL b,LL &x,LL &y)
{
if(b==0)
{
x = 1;
y = 0;
return a;
}
else {
LL r = exgcd(b,a%b,y,x);
y -= x*(a/b);
return r;
}
}
LL CRT(LL *a,LL *m,int n)
{
LL c = a[0], l = m[0];
LL d, x, y;
for(int i = 1; i < n; i++)
{
d=exgcd(l, m[i], x, y);
if((a[i]-c)%d)
return -1;
x = (a[i] - c) / d * x % (m[i] / d);
c += l * x;
l = l / d * m[i];
c %= l;
}
return c > 0 ? c : c + l;
}
int main()
{
int n;
int t;
scanf("%d",&t);
int Case=0;
while(t--)
{
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%lld",&m[i]);
for(int i=0;i<n;i++)
scanf("%lld",&a[i]);
printf("Case %d: %lld\n",++Case,CRT(a,m,n));
}
return 0;
}