hdu3597Hello Kiki 一元模线性方程组

/*
    题目描述:有一堆硬币,每堆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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值