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.
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.
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
2 2 14 57 5 56 5 19 54 40 24 80 11 2 36 20 76
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());
}
}