1. 程式人生 > >Hello Kiki HDU

Hello Kiki HDU

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. InputThe 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 OutputFor 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
2
2
14 57
5 56
5
19 54 40 24 80
11 2 36 20 76
Sample Output
Case 1: 341
Case 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());
    }
}