hdu 1573 X问题(解线性同余模方程组在给定取值范围的解)

来源:互联网 发布:算法第四版pdf 86mb 编辑:程序博客网 时间:2024/05/16 15:04

X问题

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3873    Accepted Submission(s): 1236


Problem Description
求在小于等于N的正整数中有多少个X满足:X mod a[0] = b[0], X mod a[1] = b[1], X mod a[2] = b[2], …, X mod a[i] = b[i], … (0 < a[i] <= 10)。
 

Input
输入数据的第一行为一个正整数T,表示有T组测试数据。每组测试数据的第一行为两个正整数N,M (0 < N <= 1000,000,000 , 0 < M <= 10),表示X小于等于N,数组a和b中各有M个元素。接下来两行,每行各有M个正整数,分别为a和b中的元素。
 

Output
对应每一组输入,在独立一行中输出一个正整数,表示满足条件的X的个数。
 

Sample Input
310 31 2 30 1 2100 73 4 5 6 7 8 91 2 3 4 5 6 710000 101 2 3 4 5 6 7 8 9 100 1 2 3 4 5 6 7 8 9
 

Sample Output
103
 

Author
lwg
 

Source
HDU 2007-1 Programming Contest
题目分析:
由拓展欧几里得解联立的同余模方程组求得是在a[]的最小公倍数范围内的解,因为最后结果是对lcm(a[])取模,所以要得到在给定范围的正整数解,就要加上lcm,直至超过取值范围,如果最初求得的最小的解为0,那么因为要求最终解是正整数,所以必须要去掉
#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>#define MAX 20using namespace std;typedef long long LL;LL t,n,m;LL a[MAX];LL b[MAX];void exgcd ( LL a , LL b , LL& d , LL& x , LL& y ){    if ( !b )        x = 1 , y = 0 , d = a;    else         exgcd ( b , a%b , d , y , x ) , y -= x*(a/b);}LL solve ( LL n , LL m ){    if ( n < 1 ) return 0 ;    LL ta,tb,c,d,x,y;    for ( LL i = 1 ; i < n ; i++ )    {        ta = a[0] , tb = a[i] , c = b[i] - b[0];        exgcd ( ta , tb , d , x ,y );        if ( c%d ) return 0;        LL t = tb/d;        x = (x*(c/d)%t+t)%t;        b[0] = a[0]*x+b[0];        a[0] = a[0]*(a[i]/d);    }    if ( b[0] > m ) return 0;    if ( b[0] == 0 ) return m/a[0];    return (m-b[0])/a[0] + 1;}int main ( ){    scanf ( "%lld" , &t );    while ( t-- )    {        scanf ( "%lld%lld" , &n , &m );        for ( int i = 0 ; i < m ; i++ )            scanf ( "%lld" , &a[i] );        for ( int i = 0 ; i < m ; i++ )            scanf ( "%lld" , &b[i] );        printf ( "%lld\n" , solve ( m , n ) );    }}


 
0 0
原创粉丝点击