poj 2891 解题报告

//中国剩余定理  因子非互素,所以只能两个两个得来;
// 证明:
//x = a1(mod n1);
//x = a2(mod n2);
//因为 n1- n2 不互素;
//so : x = n1* k1 + a1;
//  x = n2 *k2 + a2;
//两式相减
//n1*k1 = n2*k2 + a2-a1;
//n1 *k1 = a2-a1(mod n2);
//若k1 有解,则gcd(n1,n2)|(a2-a1);
//设 d =
gcd(n1,n2);
//n1*k1/d = (a2-a1)/d (mod n2/d);
//k1 = (a2-a1)/d * (n1/d)^-1 (mod n2/d);

//则:x = n1*((a2-a1)/d *(n1/d)^-1 )+k(n2/d) )+ a1;
//x=  n1*(a2-a1)*(n1/d)^-1 /d + a1(mod n1n2/d);
//令 t =n1*(a2-a1)*(n1/d)^-1 ,n =  n1n2/d;
//x = tn1 + a2(mod n);
//所以所有方程可以合并成一个。。。
1 #include"iostream"
 2 using namespace std;
 3 
 4 long long gcd(long long a,long long b,long long &x,long long &y  ){
 5     if(b==0){
 6         x = 1;
 7         y = 0;
 8         return a;
 9     }
10     long long ans = gcd(b,a%b,x,y);
11     long long t = x;
12     x = y;
13     y = t- a/b*y;
14     return ans;
15 }
16 int main(){
17     long long n;
18     while(cin>>n){
19         long long m1,r1,m2,r2,a,b,x,y;
20         int flag = 1,i;
21         cin>>m1>>r1;
22         for(i=1;i<n;i++){
23             cin>>m2>>r2;
24             if(!flag)
25                 continue;
26             a = gcd(m1,m2,x,y);
27             if((r2-r1)%a!=0){
28                 flag = 0;
29                 continue;
30             }
31             x = x*(r2-r1)/a;
32             b = m2/a;
33             x= (x%b+b)%b;
34             r1 = r1 + m1*x;
35             m1 = (m1*m2)/a;
36         }
37         if(flag)
38             cout<<r1<<endl;
39         else
40             cout<<-1<<endl;
41     }
42     return 0;
43 }

 

posted @ 2013-05-30 23:58  夜晓楼  阅读(166)  评论(0编辑  收藏  举报