HDU - 1573 - X问题(中国剩余定理不满足互质情况下的求解)

来源:互联网 发布:健康体检软件 编辑:程序博客网 时间:2024/06/13 04:28

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1573

题解:

推导过程太长写纸上了,夹在ACM/ICPC那本书里面。
转一个题解:
http://972169909-qq-com.iteye.com/blog/1266328
作者 (KIDx)

AC代码:

#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>using namespace std;#define LL __int64#define M 10int N;LL exgcd(LL a,LL b, LL& x, LL& y){    if(b == 0)    {        x = 1, y= 0;        return a;    }    LL re = exgcd(b, a%b, x , y);    LL tmp = x;    x = y;    y = tmp - a/b*y;    return re;}LL CRT2 (LL b[], LL n[], int num){    int i;    bool flag = false;    LL n1 = n[0], n2, b1 = b[0], b2, bb, d, t, k, x, y;    for (i = 1; i < num; i++)    {        n2 = n[i], b2 = b[i];        bb = b2 - b1;        d = exgcd(n1, n2, x, y);        if (bb % d)     //模线性解k1时发现无解        {            flag = true;            break;        }        k = bb / d * x;        t = n2 / d;        if (t < 0) t = -t;        k = (k % t + t) % t;        b1 = b1 + n1*k;        n1 = n1 / d * n2;    }    if (flag)        return 0;    if (b1 == 0)        b1 = n1;    if (b1 > N)        return 0;    return (N-b1)/n1+1;}
2 0