HDU 3579-数论训练A题 exgcd加中国剩余定理

来源:互联网 发布:淘宝店铺一心 编辑:程序博客网 时间:2024/05/29 11:16

Description

One day I was shopping in the supermarket. There was a cashier counting coins seriously when a little kid running and singing "门前大桥下游过一群鸭,快来快来 数一数,二四六七八". And then the cashier put the counted coins back morosely and count again... 
Hello Kiki is such a lovely girl that she loves doing counting in a different way. For example, when she is counting X coins, she count them N times. Each time she divide the coins into several same sized groups and write down the group size Mi and the number of the remaining coins Ai on her note. 
One day Kiki's father found her note and he wanted to know how much coins Kiki was counting.

Input

The first line is T indicating the number of test cases. 
Each case contains N on the first line, Mi(1 <= i <= N) on the second line, and corresponding Ai(1 <= i <= N) on the third line. 
All numbers in the input and output are integers. 
1 <= T <= 100, 1 <= N <= 6, 1 <= Mi <= 50, 0 <= Ai < Mi

Output

For each case output the least positive integer X which Kiki was counting in the sample output format. If there is no solution then output -1. 

Sample Input

2214 575 56519 54 40 24 8011 2 36 20 76

Sample Output

Case 1: 341Case 2: 5996

题目大意:一个小孩儿叫Kiki,喜欢计数玩儿。当她数X个硬币时,她把他们数N次,每一次她把这些硬币分成相同大小的几堆然后记下每堆的大小Mi和剩下硬币的数量Ai。
输入给出T组数据,每组第一行一个n,第二行是M1-Mn,第三行是A1-An。
输出满足条件的最小硬币数,没有则输出-1。
(即答案对Mi取余得到对应的Ai)。


      这道题要得到答案要跑很多数,用普通方法直接来是肯定会超时的,所以要搞搞算法了。先找两个同余方程 设通解为N,N=r1(mod(m1)),N=r2(mod(m2)),

可以化为k1*m1+r1=k2*m2+r2;       k1*m1+(-k2*m2)=r2-r1;

设a=m1,b=m2,x=k1,y=(-k2),c=r2-r1

方程可写为ax+by=c;

由欧几里得解得x即可,那么将x化为原方程的最小正整数解,

(x*(c/d)%(b/d)+(b/d))%(b/d);

所以N=a*(x+n*(b/d))+r1        N=(a*b/d)*n+(a*x+r1),

这里只有n为未知数所以又是一个N=(a*x+r1)(mod(a*b/d))的式子。

#include <iostream>#define LL long longusing namespace std;LL m[10],r[10];LL gcd(LL a,LL b){    return b==0?a:gcd(b,a%b);}void Ex_gcd(LL a,LL b,LL &d,LL &x,LL &y){    if(b==0)    {        x=1,y=0,d=a;    }    else    {        Ex_gcd(b,a%b,d,y,x);        y-=x*(a/b);    }}  LL china_remain(int n){    LL a,b,c,c1,c2,x,y,d,N;    a=m[0];c1=r[0];    for(int i=1;i<n;i++)    {        b=m[i];c2=r[i];        Ex_gcd(a,b,d,x,y);        c=c2-c1;        if(c%d)return -1;        LL b1=b/d;        x=((c/d*x)%b1+b1)%b1;        c1=a*x+c1;        a=a*b1;    }    if(c1==0)//当余数都为0    {        c1=1;        for(int i=0;i<n;i++)            c1=c1*m[i]/gcd(c1,m[i]);    }    return c1;}int main(){    int t,n,k;    cin>>t;    for(k=1;k<=t;k++)    {        cin>>n;        int ans=-1;        for(int i=0;i<n;i++)            cin>>m[i];        for(int i=0;i<n;i++)            cin>>r[i];           cout<<"Case "<<k<<": "<<china_remain(n)<<endl;    }    return 0;}


0 0
原创粉丝点击