/*
题目描述:有一堆硬币,每堆mi个的数剩ai个(1<= i <=6)问这堆硬币最少多少个
方法:设硬币有X个 X = mi * yi + ai , 所以有X = ai ( mod mi ),解一元模线性方程组
*/
#pragma warning(disable:4786)
#pragma comment(linker, "/STACK:102400000,102400000")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<vector>
#include<cmath>
#include<string>
#include<sstream>
#define LL long long
#define FOR(i,f_start,f_end) for(int i=f_start;i<=f_end;++i)
#define mem(a,x) memset(a,x,sizeof(a))
#define lson l,m,x<<1
#define rson m+1,r,x<<1|1
using namespace std;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const double PI = acos(-1.0);
const double eps=1e-8;
LL a[10] , m[10];
int n;
LL ex_gcd(LL a , LL b , LL &x ,LL &y)
{
if(b==0){
x = 1 ; y = 0;
return a;
}
LL d = ex_gcd(b , a%b , y , x);
y = y - a / b * x;
return d;
}
LL solve()
{
LL a1 , r1 , a2 , r2 , x0 , y0;
bool ok = 1;
a1 = m[1]; r1 = a[1];
for(int i = 2 ; i<= n ; i++){
a2 = m[i]; r2 = a[i];
LL d = ex_gcd(a1 , a2 , x0 , y0);
LL c = r2 - r1;
if(c % d){
ok = 0;
}
LL m= a2 / d;
x0 = (x0 * c / d % m + m)%m;
r1 = a1 * x0 + r1;
a1 = a1 * (a2 / d);
}
if(!ok) return -1;
if(r1 == 0) r1 += a1; //这里有一个小trick,硬币总数不能为0
return r1;
}
int main()
{
int T , kase = 0;
scanf("%d",&T);
while(T--){
scanf("%d",&n);
FOR(i , 1 , n) scanf("%lld" , &m[i]);
FOR(i , 1 , n) scanf("%lld" , &a[i]);
LL ans = solve();
printf("Case %d: %lld\n",++kase , ans);
}
return 0;
}
hdu3597Hello Kiki 一元模线性方程组
最新推荐文章于 2021-01-02 12:40:22 发布