POJ - 2891 中国剩余定理模板题
2017-08-13 22:06
399 查看
题目链接在此
题意很好懂,对于一个确定的数,选择k个不同的模数,得到相应的余数。
一般的CRT用来解决模数互素的情况,本题不一定模数互素,因此,一般的中国剩余定理模板是不够的。
记录一下AC的模板。
题意很好懂,对于一个确定的数,选择k个不同的模数,得到相应的余数。
一般的CRT用来解决模数互素的情况,本题不一定模数互素,因此,一般的中国剩余定理模板是不够的。
记录一下AC的模板。
#include<iostream> #include<cstdio> using namespace std; const int maxn = 1e6+10; typedef long long ll; typedef pair<ll,ll> pll; ll a[maxn],b[maxn],m[maxn]; ll gcd(ll a,ll b) { return b==0?a:gcd(b,a%b); } ll ex_gcd(ll a,ll b,ll& x,ll& y) { if(b==0){ x = 1,y = 0; return a; } ll d = ex_gcd(b,a%b,y,x); y -= a/b*x; return d; } ll inv(ll a,ll p) { ll d,x,y; d = ex_gcd(a,p,x,y); return d==1?(x%p+p)%p:-1; } pll CRT(int n, ll A[], ll B[], ll M[]) { ll ans = 0, m = 1; for(int i = 0; i < n; i ++) { ll a = A[i] * m, b = B[i] - A[i]*ans, d = gcd(M[i], a); if(b % d != 0) return pll(0, -1);//答案不存在,返回-1 ll t = b/d * inv(a/d, M[i]/d)%(M[i]/d); ans = ans + m*t; m *= M[i]/d; } ans = (ans % m + m ) % m; return pll(ans, m);//返回的x就是答案,m是最后的lcm值 } int main() { int k; while(~scanf("%d",&k)) { for(int i=0;i<k;i++) { a[i] = 1; scanf("%I64d %I64d",&m[i],&b[i]); } pll ans = CRT(k,a,b,m); if(ans.second==-1) printf("-1\n"); else cout<<ans.first<<endl; } }
相关文章推荐
- POJ 2891 Strange Way to Express Integers 【中国剩余定理线性模方程合并(模板)】
- poj 1006 中国剩余定理模板
- poj 2891《中国剩余定理》
- poj 1006 中国剩余定理模板
- POJ 1006 ——Biorhythms 中国剩余定理模板
- POJ 2891 Strange Way to Express Integers[中国剩余定理(非互质)][扩展欧几里得]
- poj 2891 Strange Way to Express Integers 模数不互素的中国剩余定理
- poj2891——Strange Way to Express Integers(扩展欧几里得解中国剩余定理)
- poj 1006 中国剩余定理模板
- poj 2891 Strange Way to Express Integers 模数不互素的中国剩余定理
- POJ1006生理周期----【模板】CRT中国剩余定理即孙子定理即求解一次同余方程
- POJ 2891 Strange Way to Express Integers 中国剩余定理
- poj 1006 中国剩余定理模板
- poj 2891 Strange Way to Express Integers 模数不互素的中国剩余定理
- poj 1006 中国剩余定理模板
- poj 2891 Strange Way to Express Integers——使用中国剩余定理中处理某些方程模数不互质的方法
- 一些关于中国剩余定理的数论题(POJ 2891/HDU 3579/HDU 1573/HDU 1930)
- poj 1006 中国剩余定理模板
- POJ 2891 Strange Way to Express Integers 中国剩余定理
- POJ 2891 Strange Way to Express Integers解线性同余方程组(中国剩余定理不互质版)