中国剩余定理(孙子定理)

来源:互联网 发布:通联数据 公司怎样 编辑:程序博客网 时间:2024/05/16 15:05

HDU - 3579 Hello Kiki

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


题意:

求一个最小正整数,第一行是除数,第二行是对应的余数


#include<cstdio>#include<iostream>#include<algorithm>#include<cstring>#include<string>using namespace std;const int size  = 5000 + 10; __int64ext_gcd(__int64 a,__int64 b,__int64& x,__int64& y){__int64 d = a;if (!b){x = 1;y = 0;}else{d = ext_gcd(b,a%b,y,x);y -= a/b*x;}return d;}__int64 r[size],b[size];__int64 lcm= 1;__int64 Sunzi(__int64 *b, __int64 *r, int len)//b 存放除数  r存放余数{lcm = 1;__int64 ans = 0;int i;for (i=0;i<len;i++){__int64 k0,ki;__int64 d = ext_gcd(lcm,b[i],k0,ki);if ((r[i]-ans)%d!=0) return -1;else {__int64 t = b[i]/d;k0 = ( k0*(r[i]-ans)/d%t + t)%t;ans = k0*lcm + ans;lcm = lcm/d*b[i];}}return ans;}int main(){__int64 x, y, i, j, n, m, z;int t, ca = 0;scanf("%d", &t);while(t--){int n;scanf("%d", &n);for(i = 0; i < n; i++) scanf("%I64d", &b[i]);for(i = 0; i < n; i++) scanf("%I64d", &r[i]);if(n==1&&r[0]==0) printf("Case %d: %I64d\n", ++ca, b[0]);else printf("Case %d: %I64d\n", ++ca, Sunzi(b, r, n));}return 0;}


原创粉丝点击