HDU 3579 Hello Kiki【CRT(互质+不互质)统一】

来源:互联网 发布:jvm垃圾回收算法 编辑:程序博客网 时间:2024/06/05 04:59

 Hello Kiki

Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
Submit
 
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


题意:求线性模方程组的解;

思路:mi没说,那么可能互质也可能不互质,两种情况都要考虑到,合并方程是不互质的,而互质的情况就是最小非负解是M  对m1取余后就成0了,所以当最小非负姐是0的时候要加一个条件(这样就可以把互质与不互质的情况统一起来了);

失误:刚学习没有理解那么深,还是得通过做题来找自己的不足!!!


AC代码:

#include<cstdio>int a[11],m[22];int Exgcd(int a,int b,int &x,int &y){if(!b){ x=1; y=0; return a;}int r=Exgcd(b,a%b,y,x);y-=a/b*x;return r;}int CRT(int a[],int m[],int n){    int i=0,a1=a[1],m1=m[1];for(i=2;i<=n;++i){int a2=a[i],m2=m[i];int c=a2-a1;int x=0,y=0;int d=Exgcd(m1,m2,x,y);    if(c%d) return -1;x=x*c/d;int mod=m2/d;//写错一个就不行了 x=(x%mod+mod)%mod;a1+=m1*x; m1*=mod; }    if(a1==0) a1+=m1;//互质时还原最小解为最小公倍数 m1的含义 return a1;} int main(){int T,N,i,Kase=0;scanf("%d",&T);while(T--){scanf("%d",&N);for(i=1;i<=N;++i)scanf("%d",&m[i]);for(i=1;i<=N;++i)   scanf("%d",&a[i]);printf("Case %d: %d\n",++Kase,CRT(a,m,N)); } return 0; } 



0 0
原创粉丝点击