HDU1573 X问题 解同余方程组

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1573



分析:判断同余方程组在某个范围内的解的个数,在POJ2891的基础上增加一步即可:设b数组中所有数的最小公倍数为lcm,那么我们在解出同余方程组的一个小于lcm的解r1后,令r1+k×lcm<=n(k为最终的解的个数),若r1为0,那么解出的k即为所求;若r1不为0,那么k+1即为所求。


实现代码如下:

#include <iostream>
#include <cstdio>
using namespace std;
typedef long long LL;
LL n,m,a,b,c,d,a1,r1,a2,r2;
LL A[15],B[15];
void exgcd(LL a,LL b,LL &d,LL &x,LL &y)
{//扩展欧几里得算法
    if(!b)
    {
        x=1,y=0,d=a;
        return ;
    }
    else
    {
        exgcd(b,a%b,d,x,y);
        LL temp=x;
        x=y;
        y=temp-(a/b)*y;
    }
}
int solve()
{//解出同余方程组的小于lcd(r1,r2,...,rk)的唯一解
    bool ifhave=1;
    LL x0,y0;
    a1=A[1],r1=B[1];
    for(int i=2;i<=m;i++)
    {
        a2=A[i],r2=B[i];
        a=a1,b=a2,c=r2-r1;
        exgcd(a,b,d,x0,y0);
        if(c%d) ifhave=0;
        LL t=b/d;
        x0=(x0*(c/d)%t+t)%t;
        r1=a1*x0+r1;
        a1=a1*(a2/d);
    }
    if(!ifhave) r1=-1;
    return r1;
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        scanf("%lld%lld",&n,&m);
        for(int i=1;i<=m;i++)
          scanf("%lld",&A[i]);
        for(int i=1;i<=m;i++)
          scanf("%lld",&B[i]);
        LL ans=solve();
        if(ans==-1||ans>n) puts("0");
        else
        {
            if(ans) printf("%lld\n",(n-r1)/a1+1);
            else printf("%lld\n",(n-r1)/a1);
        }
    }
    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值