fzu 1402 猪的安家 (中国剩余定理)

 Problem 1402 猪的安家

Accept: 897    Submit: 5642
Time Limit: 1000 mSec    Memory Limit : 32768 KB

 Problem Description

Andy和Mary养了很多猪。他们想要给猪安家。但是Andy没有足够的猪圈,很多猪只能够在一个猪圈安家。举个例子,假如有16头猪,Andy建了3个猪圈,为了保证公平,剩下1头猪就没有地方安家了。Mary生气了,骂Andy没有脑子,并让他重新建立猪圈。这回Andy建造了5个猪圈,但是仍然有1头猪没有地方去,然后Andy又建造了7个猪圈,但是还有2头没有地方去。Andy都快疯了。你对这个事情感兴趣起来,你想通过Andy建造猪圈的过程,知道Andy家至少养了多少头猪。

 Input

输入包含多组测试数据。每组数据第一行包含一个整数n (n <= 10) – Andy建立猪圈的次数,解下来n行,每行两个整数ai, bi( bi <= ai <= 1000), 表示Andy建立了ai个猪圈,有bi头猪没有去处。你可以假定(ai, aj) = 1.

 Output

输出包含一个正整数,即为Andy家至少养猪的数目。

 Sample Input

3 3 1 5 1 7 2

 Sample Output

16

 Source

Andy Zhau's Contest No.1

模板题:

 1 /*
 2 Accepted    
 3 1402
 4 GNU C++
 5 0 ms    208KB    827B    
 6 */
 7 #include<stdio.h>
 8 __int64  a[15],b[15];
 9 __int64 extend_euclid(__int64 a0,__int64 b0,__int64 &x,__int64 &y)
10 {
11     if(b0==0){
12         x=1;y=0;
13         return a0;
14     }
15     __int64 d=extend_euclid(b0,a0%b0,x,y);
16     __int64 t=x;
17     x=y;
18     y=t-a0/b0*y;
19     return d;
20 }
21 __int64 china_reminder(int n)
22 {
23     __int64 N=1;
24     __int64 ans=0;
25     for(int i=0;i<n;i++)
26         N*=a[i];
27     for(int i=0;i<n;i++){
28         __int64 m=N/a[i];
29         __int64 x,y;
30         extend_euclid(m,a[i],x,y);
31         x=(x%a[i]+a[i])%a[i]; 
32         ans=(ans+m*b[i]*x%N)%N;
33     }
34     return ans;
35 } 
36 int main(void)
37 {
38     int n;
39     while(scanf("%d",&n)!=EOF)
40     {
41         for(int i=0;i<n;i++)
42             scanf("%I64d%I64d",&a[i],&b[i]);
43         printf("%I64d
",china_reminder(n));
44     }
45     return 0;
46 }
原文地址:https://www.cnblogs.com/GO-NO-1/p/3785168.html