Time Limit: 1000MS | Memory Limit: 131072K | |
Total Submissions: 9658 | Accepted: 2931 |
Description
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
2 8 7 11 9
Sample Output
31
题意: 给k对(ai,ri),解模线性方程组 m ≡ ri (mod) ai 判定是否有解,求最小解。有一点比较有问题就是题目的Hint,说输入输出数字均在__int64内。显然k也包进去了!显然这是不可能的!想像下__int64个方程,O(n)也要超时啊!所以k还是按int来。由于k不定,且ai 不互质,因此采用两两合并解的方法。首先拿前两个方程, m ≡ r1 (mod) a1 m ≡ r2 (mod) a2两式等同于 m = a1*x1 + r1 m = a2*x2 + r2前式代入后式,消去m可得 a1*x1 = a2*x2 + r2 - r1写成模方程,去一个未知数x2, a1*x1 ≡ r2 - r1 (mod) a2 ---@ 扩展GCD可判定是否有解,若此方程无解,则后面所有方程都无需判定。若有解,则能求出所有的解,然后代回方程 m = a1*x1 + r1得到每个可能的 m。 但是在此,求出所有的解然后向下面每个方程测试显然有些不现实而能得到的最小解以及这一解系的关系应当能写成相同模方程的形式。看了很多份解题报告也没理解这个解系的方程是怎么写出来的每一份解题报告写到这里都只有一句显然就给带过了。反正我是个弱菜,我是没看出来它是怎么显然的。@式的最小解x,解系x1 = x + i*(a2 / d) (d = gcd(a1,a2) , i = 0~d - 1) 这一点是已知的,在扩展GCD中可求的然后把x 求出来,得到方程 m ≡ a1 * x + r1 (mod) ( lcm (a1, a2))
代码如下:
#include<iostream> #include<cstdio> #include<memory.h> using namespace std; __int64 k,m,t; __int64 extend_euclid(__int64 a,__int64 b,__int64 &x,__int64 &y) { if(b==0) { x=1; y=0; return a; } __int64 d=extend_euclid(b,a%b,x,y); t=x; x=y; y=t-a/b*y; return d; } int main() { int i,flag; __int64 p,q,d,a1,a2,b1,b2,x,c; while(scanf("%I64d",&k)!=EOF) { scanf("%I64d%I64d",&b1,&a1); flag=0; for(i=0;i<k-1;i++) { scanf("%I64d%I64d",&b2,&a2); if(flag) continue; d=extend_euclid(b1,b2,p,q); c=a2-a1; if(c%d) { flag=1; continue; } t=b2/d; x=(c/d*p%b2+b2)%t;// c/d*p可能为负数,要先模一个b2 a1=x*b1+a1; b1=b1*b2/d;//b1=lcm(b1,b2) } if(flag) puts("-1"); else printf("%I64d\n",a1); } return 0; }
详细欧几里得算法:http://blog.csdn.net/jiangx1994/article/details/38051485