POJ 2891
中国剩余定理的扩展
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<iostream> 2 #include<cstdio> 3 #include<vector> 4 using namespace std; 5 typedef long long int ll; 6 ll exgcd(ll a, ll b, ll &x, ll &y) 7 { 8 if (b == 0) { 9 x = 1; 10 y = 1; 11 return a; 12 } 13 ll d = exgcd(b,a%b,x,y); 14 ll t = x; 15 x = y; 16 y = t - a/b*y; 17 return d; 18 } 19 20 ll get_res(vector<ll> &a, vector<ll> &r) 21 { 22 ll A(a[0]),R(r[0]),x,y,d; 23 for (int i(1); i<a.size(); ++i) { 24 d = exgcd(A,a[i],x,y); 25 ll c = r[i] - R; 26 if (c%d)return -1; 27 ll a1 = abs(a[i]/d); 28 x = x*c/d; 29 x = (x%a1 + a1)%a1; 30 R += A*x; 31 A *= a[i]/d; 32 } 33 return R; 34 } 35 36 37 int main() 38 { 39 int n; 40 while (scanf("%d",&n) != EOF) { 41 vector<ll> a; 42 vector<ll> r; 43 ll aa,rr; 44 for (int i(0); i<n; ++i) { 45 scanf("%I64d%I64d",&aa,&rr); 46 a.push_back(aa); 47 r.push_back(rr); 48 } 49 ll R = get_res(a,r); 50 cout<<R<<endl; 51 } 52 }