1. 程式人生 > >Hdu 1573 X問題 中國剩餘定理模板

Hdu 1573 X問題 中國剩餘定理模板

 

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

 

3

10 3

1 2 3

0 1 2

100 7

3 4 5 6 7 8 9

1 2 3 4 5 6 7

10000 10

1 2 3 4 5 6 7 8 9 10

0 1 2 3 4 5 6 7 8 9

 

 

Sample Output

 

1

0

3

中國剩餘定理的模板題目...

求出最小數之後再累加上他們的最小公倍數求個數....

要注意求的是正整數,如果求出為最小數為0的話,需要減一....

程式碼入下:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn=15;
typedef __int64 ll;
int t;
ll a[maxn],b[maxn];
ll n,m;
ll Extend (ll A,ll B,ll& X,ll& Y)
{
    if(B==0)
    {
        X=1; Y=0;
        return A;
    }
    else
    {
        ll temp,ans;
        ans=Extend (B,A%B,X,Y);
        temp=X;
        X=Y;
        Y=temp-A/B*Y;
        return ans;
    }
}
void solve ()
{
    int sum=0;
    ll x,y,d,t,c;
    for (int i=1;i<m;i++)
    {
        c=b[i]-b[i-1];
        d=Extend(a[i-1],a[i],x,y);
        if(c%d)
        {
            printf("0\n");
            return;
        }
        x=c/d*x;
        t=a[i]/d;
        x=(x%t+t)%t;
        b[i]=a[i-1]*x+b[i-1];
        a[i]=a[i]/d*a[i-1];
    }
    if(b[m-1]==0)
        b[m-1]=a[m-1];
    for (ll i=b[m-1];i<=n;i+=a[m-1])
          sum++;
    printf("%d\n",sum);
}
int main()
{
    scanf("%d",&t);
    while (t--)
    {
       scanf("%I64d%I64d",&n,&m);
       for (ll i=0;i<m;i++)
            scanf("%I64d",&a[i]);
       for (ll i=0;i<m;i++)
            scanf("%I64d",&b[i]);
       solve();
    }
    return 0;
}