POJ - 2891 Strange Way to Express Integers (扩展中国剩余定理)
扩展CRT模板题,原理及证明见传送门(引用)
1 #include<cstdio> 2 #include<algorithm> 3 using namespace std; 4 typedef long long ll; 5 const ll N=1e5+10; 6 ll n,m[N],c[N]; 7 void exgcd(ll a,ll b,ll& x,ll& y,ll& g) { 8 if(!b)x=1,y=0,g=a; 9 else exgcd(b,a%b,y,x,g),y-=x*(a/b); 10 } 11 bool CRT(ll& c1,ll& m1,ll c2,ll m2) { 12 ll y1,y2,g; 13 exgcd(m1,m2,y1,y2,g); 14 if((c1-c2)%g)return 0; 15 y1*=(c1-c2)/g,c1-=y1%(m2/g)*m1,m1*=m2/g,c1=(c1+m1)%m1; 16 return 1; 17 } 18 ll solve() { 19 ll C=0,M=1; 20 for(ll i=0; i<n; ++i)if(!CRT(C,M,c[i],m[i]))return -1; 21 return C; 22 } 23 24 int main() { 25 while(scanf("%lld",&n)==1) { 26 for(ll i=0; i<n; ++i)scanf("%lld%lld",&m[i],&c[i]); 27 printf("%lld\n",solve()); 28 } 29 return 0; 30 }