HDU 3579

时间:2023-03-09 04:15:21
HDU 3579

标准同余方程组,只是在求出值后如果为0,应该输出Mi的Lcm;

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long LL;
LL Ai[50],Ri[50];
LL gcd(LL a, LL b)
{
return b ? gcd(b,a%b) : a;
}
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 -= x*(a/b); }
}
LL ModN(LL* Ai,LL* Ri,LL n)
{
LL a1 = Ai[1], r1 = Ri[1];
LL X,Y,D;
bool Jug = true;
for(LL i = 2; i <= n; ++i)
{
//if(Jug == false) break;
LL a = a1, b = Ai[i], c = Ri[i] - r1;
Exgcd(a,b,D,X,Y);
if(c % D)
{
Jug = false;
return -1;
}
LL t = b / D;
X = (X * (c / D) % t + t) % t;
r1 += a1 * X;
a1 *= Ai[i] / D;
}
return r1;
}
int main()
{
int t;
LL N;
int Case = 1;
cin >> t;
while(t --)
{
cin >> N;
for(int i = 1; i <= N; ++i)
cin >> Ai[i];
for(int i = 1; i <= N; ++i)
cin >> Ri[i];
LL ans = ModN(Ai,Ri,N);
printf("Case %d: ",Case++);
if(ans == -1) cout << "-1\n";
else if(ans != 0) cout << ans << endl;
else {
LL Lcm = 1;
for(int i = 1; i <= N; ++i)
Lcm = Lcm / gcd(Lcm,Ai[i]) * Ai[i];
cout << Lcm << endl;
}
}
}