POJ 2891 Strange Way to Express Integers (扩展欧几里得)

网友投稿 774 2022-08-26

POJ 2891 Strange Way to Express Integers (扩展欧几里得)

POJ 2891 Strange Way to Express Integers (扩展欧几里得)

Description

Elina is reading a book written by Rujia Liu, which introduces a strange way to express non-negative integers. The way is described as following:Choose k different positive integers a1, a2, …, ak. For some non-negative m, divide it by every ai (1 ≤ i ≤ k) to find the remainder ri. If a1, a2, …, ak are properly chosen, m can be determined, then the pairs (ai, ri) can be used to express m.“It is easy to calculate the pairs from m, ” said Elina. “But how can I find m from the pairs?”Since Elina is new to programming, this problem is too difficult for her. Can you help her?

Input

The input contains multiple test cases. Each test cases consists of some lines.Line 1: Contains the integer k.Lines 2 ~ k + 1: Each contains a pair of integers ai, ri (1 ≤ i ≤ k).

Output

Output the non-negative integer m on a separate line for each test case. If there are multiple possible values, output the smallest one. If there are no possible values, output -1.

Sample Input

28 711 9

Sample Output

31

题意

给出一组 mi,ri ,求最小的一个正整数 X ,使得 X%mi=ri ,如果不存在这样的 X 则输出 −1

思路

因为除数之间不满足两两互质,所以就不能直接套用中国剩余定理的模板咯!

这里我们采用合并 不定方程 的方法,即先合并前两个方程,然后用合并的结果与第三个方程进行合并,最终合并完之后计算得到的 X

我们假设 mi 是除数, ri

X%m0=r0 与 X%m1=r1 ,等价于 X=m0×k0+ro=m1×k1+r1 ,其中 ki

联立可得 m0×k0+m1×k1=r1−r0 (因为 ki

扩展欧几里得算法中说:存在整数对 (x,y) 使得 ax+by=gcd(a,b)

于是我们可以根据上面联立得出的式子构造出 m0x+m1y=gcd(m0,m1)

通过 ex_gcd 可以求出 gcd(m0,m1) 以及 x,y

于是便有 k0=x×r1−r0gcd(m0,m1)

带回原来的式子可以解得 X=m0×k0+r0 ,此时 X 的通解为 X′=X+k×lcm(m0,m1) ( k 为一整数,想要让 X′%m0=r0,X′%m1=r1 这两个式子同时成立,X 每次增加的步长应该是 lcm(m0,m1)

上式可转化成: X′%lcm(m0,m1)=X

于是这两个方程便合并啦~

合并完所有的方程以后,输出最小的正整数 X′

关于代码中求 k0 modmigcd(M,mi)

a×x0+b×y0=gcd(a,b) 等同于 a×x0+a×bgcd(a,b)k+b×y0−a×bgcd(a,b)k=gcd(a,b)

即 a×(x0+bgcd(a,b)k)+b×(y0−agcd(a,b)k)=gcd(a,b)

通解为 x=x0+bgcd(a,b)k , y=y0−agcd(a,b)k ,其中 k=...−2,−1,0,1,2...

于是在所有解中 x 的最小正整数解为 (x0+bgcd(a,b))%bgcd(a,b) , y

所以 modmigcd(M,mi) 保证了 k0

AC 代码

#include#include#include#include#include#includeusing namespace std;#include#include#define INF (1<<25)typedef __int64 LL;#define maxn 10005LL m[maxn],r[maxn];int n;LL ex_gcd(LL a, LL b, LL &x, LL &y){ LL d = a; if(b != 0) { d = ex_gcd(b, a % b, y, x); y -= (a/b) * x; } else x = 1, y = 0; return d;}LL solve(){ LL M=m[0],R=r[0],gcd,x,y; for(int i=1; i

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:JDBC的总结(简述jdbc的步骤)
下一篇:POJ 3101 Astronomy (数学)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~