POJ 2891 Strange Way to Express Integers(非互质中国剩余定理)
2017-05-03 10:30
393 查看
为了解决非互质中国剩余定理问题,需要合并方程,合并之后再按照互质的情况进行处理即可
#include <iostream> #include <cstdio> #include <cstring> using namespace std; typedef __int64 int64; int64 Mod; int64 Gcd(int64 a, int64 b) { if(b==0) return a; return Gcd(b,a%b); } int64 EX_Gcd(int64 a, int64 b, int64&x, int64& y) { if(b==0) { x=1,y=0; return a; } int64 d = EX_Gcd(b,a%b,x,y); int64 t = x; x = y; y = t - a/b*y; return d; } int64 inv(int64 a, int64 n) { int64 x,y; int64 t = EX_Gcd(a,n,x,y); if(t != 1) return -1; return (x%n+n)%n;//返回逆元(最小的正整数解X) } bool Merge(int64 a1, int64 n1, int64 a2, int64 n2, int64& a3, int64& n3) { int64 d = Gcd(n1,n2); int64 c = a2-a1; if(c%d) return false; c = (c%n2+n2)%n2; c /= d; n1 /= d; n2 /= d; c *= inv(n1,n2); c %= n2; c *= n1*d; c += a1; n3 = n1*n2*d; a3 = (c%n3+n3)%n3; return true; } int64 China_Reminder(int len, int64* a, int64* n) { int64 a1=a[0],n1=n[0]; int64 a2,n2; for(int i = 1; i < len; i++) { int64 aa,nn; a2 = a[i],n2=n[i]; if(!Merge(a1,n1,a2,n2,aa,nn)) return -1; a1 = aa; n1 = nn; } Mod = n1; return (a1%n1+n1)%n1; } int64 a[1000],b[1000]; int main() { int k; while(~scanf("%d",&k)) { for(int i = 0; i < k; i++) scanf("%I64d %I64d",&a[i],&b[i]); printf("%I64d\n",China_Reminder(k,b,a)); } return 0; }
相关文章推荐
- POJ 2891 Strange Way to Express Integers【模线性方程组】(中国剩余定理非互质套用)
- POJ 2891 Strange Way to Express Integers解线性同余方程组(中国剩余定理不互质版)
- POJ 2891 Strange Way to Express Integers 中国剩余定理MOD不互质数字方法
- poj 2891 Strange Way to Express Integers——使用中国剩余定理中处理某些方程模数不互质的方法
- poj 2891 Strange Way to Express Integers (中国剩余定理不互质)
- POJ 2891 Strange Way to Express Integers[中国剩余定理(非互质)][扩展欧几里得]
- lightoj 1319 - Monkey Tradition 中国剩余定理(孙子定理)+poj 2891 Strange Way to Express Integers
- poj 2891 Strange Way to Express Integers (非互质的中国剩余定理)
- 中国剩余定理 poj 2891 Strange Way to Express Integers
- poj2891——Strange Way to Express Integers(扩展欧几里得解中国剩余定理)
- PKU 2891:Strange Way to Express Integers(中国剩余定理非互质)
- POJ-2891 Strange Way to Express Integers 中国剩余定理
- poj 2891 Strange Way to Express Integers(扩展欧几里得,中国剩余定理)
- pog 2891 Strange Way to Express Integers (中国剩余定理 非互质)
- poj 2981 Strange Way to Express Integers (中国剩余定理不互质)
- poj 2891 Strange Way to Express Integers 模数不互素的中国剩余定理
- poj 2891 Strange Way to Express Integers 模数不互素的中国剩余定理
- poj 2891 Strange Way to Express Integers 中国剩余定理
- POJ 2891 Strange Way to Express Integers 【中国剩余定理线性模方程合并(模板)】
- POJ 2891 Strange Way to Express Integers 中国剩余定理