您的位置:首页 > 其它

HDOJ 1573 X问题(中国剩余定理非互质版本)

2016-03-08 17:53 387 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1573

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define LL __int64
using namespace std;
LL n,k,m[100],a[100];//模数为m,余数为a, X % m = a
LL T, N, m0, a0;
//m不互素
LL extend_gcd(LL a, LL b, LL &x, LL &y)
{
if(a == 0 && b == 0)return -1;
if(b ==0 ){x = 1; y = 0;return a;}
LL d = extend_gcd(b,a%b,y,x);
y -= a/b*x;
return d;
}
bool solve(LL &m0, LL &a0, LL m, LL a)
{
LL y,x;
LL g = extend_gcd(m0,m,x,y);
if (abs(a - a0)%g)
return false;
x *= (a - a0)/g;
x %= m/g;
a0 = (x*m0 + a0);
m0 *= m/g;
a0 %= m0;
if( a0 < 0 )a0 += m0;
return true;
}
/*
* 无解返回false,有解返回true;
* 解的形式最后为 a0 + m0 * t (0<=a0<m0) a0是最小的非负整数解
*/
bool MLES(LL &m0, LL &a0, LL n)//解为 X = a0 + m0 * k
{
bool flag = true;
m0 = 1;
a0 = 0;
for(int i = 0; i < n; i++)
if( !solve(m0,a0,m[i],a[i]) )
{
flag = false;
break;
}
return flag;
}
int main()
{
scanf("%I64d", &T);
while (T--)
{
scanf("%I64d%I64d", &N, &n);
for (int i = 0; i < n; i++) scanf("%I64d", &m[i]);
for (int i = 0; i < n; i++) scanf("%I64d", &a[i]);
if(!MLES(m0, a0, n) || a0 > N)
printf("0\n");
else
{
if(!a0)
printf("%I64d\n",(N-a0)/m0);
else
printf("%I64d\n",(N-a0)/m0+1);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: