Hello Kiki
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4255 Accepted Submission(s): 1644
Problem 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
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
Author
digiter (Special Thanks echo)
Source
2010 ACM-ICPC Multi-University Training Contest(14)——Host by BJTU
一道模板题……
大致题意是,要数硬币,总共数N次,第i次数,把硬币分为mi个一组,最后剩下了ai个。问你总共有多少个硬币。
正常来说,根据题目我们可以列出一系列同余方程组:n≡a1(mod m1),n≡a2(mod m2)……看着就知道是利用中国剩余定理(CRT),但是实际上定理有一个条件,那就是所有的除数mi都要互质,而显然这里的mi不一定是互质的,所以得用别的方法。
对于两个方程,n=m1*k1+a1和n=m2*k2+a2,我们可以尝试对他们进行合并。m1*k1+a1=m2*k2+a2,可以转换为m1*k1=a2-a1(mod m2),设gcd=gcd(m1,m2),则有m1*k1/gcd-m2*k2/gcd=(a2-a1)/gcd,看a2-a1是否能整除gcd可以判断是否有解。然后利用ex_gcd可以求出k1=K(mod m2/gcd)。那么就可以得到一条新的式子x=m1*K+a1(mod m1*m2/gcd)利用这条新的式子继续与后面的式子合并,一直到最后即可求出答案。由于本质上还是同余方程组,所以就称之为拓展中国剩余定理ex_CRT。模板题没什么好说的了,具体见代码:
#include <bits/stdc++.h>
#define mod 1000000007
#define LL long long
#define N 110
using namespace std;
LL m[N],r[N];
int n;
LL ex_gcd(LL a,LL b,LL &x,LL &y)
{
if(b==0){x=1,y=0;return a;}
else
{
LL r=ex_gcd(b,a%b,y,x);
y-=x*(a/b); return r;
}
}
LL ex_CRT(LL m[],LL r[],int n)
{
LL M=m[1],R=r[1];
for(int i=2;i<=n;i++)
{
LL x,y,gcd;
gcd=ex_gcd(M,m[i],x,y);
if ((r[i]-R)%gcd) return -1;
x=(r[i]-R)/gcd*x%(m[i]/gcd);
R+=x*M; M=M/gcd*m[i]; R%=M;
}
return R>0?R:R+M;
}
int main()
{
int T_T,T=0;
scanf("%d",&T_T);
while(T_T--)
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%I64d",&m[i]);
for(int i=1;i<=n;i++)
scanf("%I64d",&r[i]);
printf("Case %d: %I64d\n",++T,ex_CRT(m,r,n));
}
}