标签:des style class blog code java
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1943 Accepted Submission(s): 693
模板题,注意ans=0的情况,题目要求的是最小的正整数。
1 //0MS 244K 1571 B C++ 2 #include<stdio.h> 3 __int64 gcd(__int64 a,__int64 b) 4 { 5 return b?gcd(b,a%b):a; 6 } 7 __int64 extend_euclid(__int64 a,__int64 b,__int64 &x,__int64 &y) 8 { 9 if(b==0){ 10 x=1;y=0; 11 return a; 12 } 13 __int64 d=extend_euclid(b,a%b,x,y); 14 __int64 t=x; 15 x=y; 16 y=t-a/b*y; 17 return d; 18 } 19 __int64 inv(__int64 a,__int64 n) 20 { 21 __int64 x,y; 22 __int64 t=extend_euclid(a,n,x,y); 23 if(t!=1) return -1; 24 return (x%n+n)%n; 25 } 26 bool merge(__int64 a1,__int64 n1,__int64 a2,__int64 n2,__int64 &a3,__int64 &n3) 27 { 28 __int64 d=gcd(n1,n2); 29 __int64 c=a2-a1; 30 if(c%d) return false; 31 c=(c%n2+n2)%n2; 32 c/=d; 33 n1/=d; 34 n2/=d; 35 c*=inv(n1,n2); 36 c%=n2; 37 c*=n1*d; 38 c+=a1; 39 n3=n1*n2*d; 40 a3=(c%n3+n3)%n3; 41 return true; 42 } 43 __int64 china_reminder2(int len,__int64 *a,__int64 *n,__int64 &lcm) 44 { 45 __int64 a1=a[0],n1=n[0]; 46 __int64 a2,n2; 47 for(int i=1;i<len;i++){ 48 __int64 aa,nn; 49 a2=a[i],n2=n[i]; 50 if(!merge(a1,n1,a2,n2,aa,nn)) return -1; 51 a1=aa; 52 n1=nn; 53 } 54 lcm=n1; 55 return (a1%n1+n1)%n1; 56 } 57 int main(void) 58 { 59 int t,n,k=1; 60 __int64 a[10],b[10],lcm; 61 scanf("%d",&t); 62 while(t--) 63 { 64 scanf("%d",&n); 65 for(int i=0;i<n;i++) 66 scanf("%I64d",&a[i]); 67 for(int i=0;i<n;i++) 68 scanf("%I64d",&b[i]); 69 printf("Case %d: ",k++); 70 __int64 ans=china_reminder2(n,b,a,lcm); 71 if(ans==0) ans+=lcm; 72 printf("%I64d\n",ans); 73 } 74 return 0; 75 }
hdu 3579 Hello Kiki (中国剩余定理),布布扣,bubuko.com
标签:des style class blog code java
原文地址:http://www.cnblogs.com/GO-NO-1/p/3785685.html