hdu1573 X问题 一元模线性方程组

来源:互联网 发布:fdd lte网络 编辑:程序博客网 时间:2024/06/11 10:58
/*    题目描述:给出含m(1<= m <= 10)个形如x=bi (mod ai)的模线性方程组,问该方程组小于等于(1 <= n <= 1e9)              的解有多少个?        方法:正常解一元模线性方程组,自上向下合并,直至仅剩一个方程x = r (mod lcm(a1 ,a2 ,...,am)),若r > n 无解;          否则令r+lcm*x <= n,解出x,若r不等于0则x++,x即为答案*/#pragma warning(disable:4786)#pragma comment(linker, "/STACK:102400000,102400000")#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<stack>#include<queue>#include<map>#include<set>#include<vector>#include<cmath>#include<string>#include<sstream>#define LL long long#define FOR(i,f_start,f_end) for(int i=f_start;i<=f_end;++i)#define mem(a,x) memset(a,x,sizeof(a))#define lson l,m,x<<1#define rson m+1,r,x<<1|1using namespace std;const int INF = 0x3f3f3f3f;const int mod = 1e9 + 7;const double PI = acos(-1.0);const double eps=1e-8;LL a[15], b[15];LL n , m;LL ex_gcd(LL a , LL b , LL &x ,LL &y){    if(b==0){        x = 1 ;     y = 0;        return a;    }    LL d = ex_gcd(b , a%b , y , x);    y = y - a / b * x;    return d;}LL solve(){    LL a1 , r1 , a2 , r2 , x0 , y0;    bool ok = 1;    a1 = a[1];      r1 = b[1];    for(int i = 2 ; i <= m ; i++){        a2 = a[i] ;     r2 = b[i];        LL d = ex_gcd(a1 , a2 , x0 , y0);        LL c = r2 - r1;        if(c % d){            ok = 0;        }        LL m= a2 / d;        x0 = (x0 * c / d % m + m)%m;        r1 = a1 * x0 + r1;        a1 = a1 * (a2 / d);    }    if(!ok)     return -1;    else{        if(n < r1)      return -1;        LL ret = (n - r1 ) / a1 ;        if(r1 !=0)      ++ret ;        return ret;    }}int main(){    int T  ;    scanf("%d",&T);    while(T--){        scanf("%lld%lld",&n,&m);        FOR(i , 1 , m)  scanf("%lld",&a[i]);        FOR(i , 1 , m)  scanf("%lld",&b[i]);        LL ans = solve();        if(ans != -1)            printf("%lld\n",ans);        else            printf("0\n");    }    return 0;}

0 0
原创粉丝点击