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 
 8 void exgcd(ll a,ll b,ll& x,ll& y,ll& g) {
 9     if(!b)x=1,y=0,g=a;
10     else exgcd(b,a%b,y,x,g),y-=x*(a/b);
11 }
12 ll CRT() {
13     ll M=1,C=0,x,y,g;
14     for(ll i=0; i<n; ++i) {
15         exgcd(M,m[i],x,y,g);
16         if((c[i]-C)%g)return -1;
17         C=x*((c[i]-C)/g)%(m[i]/g)*M+C;
18         M=M*m[i]/g,C%=M;
19     }
20     return (C%M+M)%M;
21 }
22 
23 int main() {
24     while(scanf("%lld",&n)==1) {
25         for(ll i=0; i<n; ++i)scanf("%lld%lld",&m[i],&c[i]);
26         printf("%lld\n",CRT());
27     }
28     return 0;
29 }

猜你喜欢

转载自www.cnblogs.com/asdfsag/p/10432465.html