题目链接: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;
}
本文介绍了解决同余方程组在特定范围内解的数量的方法,通过扩展欧几里得算法找到一个小于最小公倍数的解,并计算出解的总数。
1638

被折叠的 条评论
为什么被折叠?



