解题报告 之 POJ2891 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 remainderri. 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
题目大意:现在将数表示成一种新的形式,即用一个数去除多个数mk,分别得到余数rk,用这些(除数,余数)对来唯一确定本来的数字。有了数num和m1~mn很容易表示成这种形式,但是现在反过来,给你n个(mk,rk)对,让你确定这个数num是多少?不存在输出-1.
分析:裸的解线性同余方程组,说实话我看书没看懂这个代码的原理,特别是要用m2/gcd那里,所以先把代码当接口来用吧。有一个讲解的比较好的博文大家可以看看原理(http://blog.csdn.net/orpinex/article/details/6972654),但是我同样看不懂,等学了中国剩余再返回来看看吧。那么这道题等价于解方程:
x ≡ r1(mod m1)
x ≡ r2(mod
m2)
……
x ≡ rn(mod
mn)
是线性同余方程组,用模版过吧,虽然原理还不懂。。。Orz。。如果有好心的大神愿意给我讲讲麻烦加我QQ吧 452884244,叩谢。
上代码:
#include<iostream> #include<algorithm> using namespace std; typedef long long ll; ll exgcd( ll a, ll b, ll& x, ll& y ) //扩展gcd { if(b == 0) { x = 1; y = 0; return a; } ll gcd = exgcd( b, a%b, x, y ); ll tem = x; x = y; y = tem - a / b*y; return gcd; } int main() { int n; ll r1, m1, r2, m2, x0, y0; while(cin >> n) { bool flag=1; cin >> m1 >> r1; //以第一个同余方程作为基础 for(int i = 1; i < n; i++) { cin >> m2 >> r2; //处理剩下的同余方程 ll a = m1, b = m2, c = r2 - r1; ll d=exgcd( a, b, x0, y0 ); //求基础解X0和d=GCD if(c%d != 0) flag = false; //无解条件 ll t = b / d; //看不懂,似乎是在更新一些系数。 x0 = (x0*(c / d) % t + t) % t; //看不懂,似乎是在更新一些系数。 r1 = m1*x0 + r1; //看不懂,似乎是在更新一些系数。 m1 = m1*(m2 / d); //看不懂,似乎是在更新一些系数。 } if(!flag) { cout << -1 << endl; continue; } cout << r1 << endl; } return 0; }
数论难起来真是理解无力。。。。