I

来源:互联网 发布:少儿编程哪家好 编辑:程序博客网 时间:2024/05/31 19:30

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

题意:求最小的数m满足ai*x+bi=m,(x为正整数)

题解:a1*x+b1=ai*y+bi,移项进行欧几里德扩展。

#include<iostream>#include<stdio.h>#include<algorithm>using namespace std;int a[10],m[10],t,n;int gcd(int a,int b){    return b?gcd(b,a%b):a;}void exgcd(int a,int b,int &d,int &x,int &y){    if(!b) d=a,x=1,y=0;    else   exgcd(b,a%b,d,y,x),y-=x*(a/b);}int solve(){    int x,y,d,A=a[0],M=m[0];    for(int i=1;i<n;i++){        exgcd(M,m[i],d,x,y);        if((a[i]-A)%d) return -1;        x=(a[i]-A)/d*x%(m[i]/d);        A+=x*M;        M=M/d*m[i];        A%=M;    }    return A>0?A:A+M;}int main(){    scanf("%d",&t);    for(int c=1;c<=t;c++){        scanf("%d",&n);        for(int i=0;i<n;i++) scanf("%d",&m[i]);        for(int i=0;i<n;i++) scanf("%d",&a[i]);        printf("Case %d: %d\n",c,solve());    }}