ramay7

https://ramay7.github.io/

HDU 1573 X问题(中国剩余定理)

题目链接
HDU 1573 X问题
题意:
求解在(0, N]区间满足 x ≡ a[i](mod m[i])(0<= i < M)的x的个数。
分析:
利用中国剩余定理求解出最小非负整数解a0(如果有解)和解的周期m0,假设解的个数为k个
则:a0 + k * m0 <= N –> k <= (N - a0) / m0,(N >= a0)
当a0 = 0时解的个数是(N - a0) / m0.
当a0 > 0时解的个数是(N - a0) / m0 + 1.

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <climits>
#include <cmath>
#include <ctime>
#include <cassert>
#define IOS ios_base::sync_with_stdio(0); cin.tie(0);
using namespace std;

typedef long long ll;
const int MAX_N = 15;

int T, M;
ll N, a0, m0, a[MAX_N], m[MAX_N];

ll ex_gcd(ll aa, ll bb, ll& xx, ll& yy)
{
    if(bb == 0) {
        xx = 1, yy = 0;
        return aa;
    }
    ll dd = ex_gcd(bb, aa % bb, yy, xx);
    yy -= aa / bb * xx;
    return dd;
}

//求解: m0 * x = (aa - a0) (mod mm)
bool ModularLinearEquation(ll& m0, ll& a0, ll mm, ll aa) 
{
    ll x, y, d;
    d = ex_gcd(m0, mm, x, y);
    if(labs(aa - a0) % d != 0) return false;
    mm /= d;
    x = x * (aa - a0) / d % mm;
    a0 += x * m0;
    m0 *= mm;
    a0 = (a0 % m0 + m0) % m0;
    return true;
}

bool CRT(ll& m0, ll&a0)
{
    bool flag = true;
    m0 = 1, a0 = 0; //任意数 mod m0 = a0恒成立
    for(int i = 0; i < M; i++){
        if(ModularLinearEquation(m0, a0, m[i], a[i]) == false){
            flag = false;
            break;
        }
    }
    return flag;
}

int main()
{
    scanf("%d", &T);
    while(T--){
        scanf("%lld%d", &N, &M);
        for(int i = 0; i < M; i++){
            scanf("%lld", &m[i]);
        }
        for(int i = 0; i < M; i++){
            scanf("%lld", &a[i]);
        }
        if(CRT(m0, a0) == false || N < a0) printf("0\n");
        else {
            //printf("a0 = %lld m0 = %lld\n", a0, m0);
            printf("%lld\n", (N - a0) / m0 + (a0 == 0 ? 0 : 1));
        }
    }
    return 0;
}
阅读更多
版权声明:缥缈玉京人,想语然、京兆眉妩。 https://blog.csdn.net/Ramay7/article/details/51542466
个人分类: 数论 HDU
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

HDU 1573 X问题(中国剩余定理)

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭