[POJ 2891] Strange Way to Express Integers【扩展中国剩余定理】

  • 2018-02-20
  • 0
  • 0

Problem:

Time Limit: 1000MS Memory Limit: 131072K

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 ≤ ik) 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 ≤ ik).

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

Hint

All integers in the input and the output are non-negative and can be represented by 64-bit integral types.

Source

POJ Monthly--2006.07.30, Static

Solution:

本题是扩展中国剩余定理的应用。

题目很不良心地没有 k 的范围,也没有保证过程不会溢出

考虑合并两个同余方程:

  • x ≡ a1 (mod m1)
  • x ≡ a2 (mod m2)

该方程组等价于:

  • x = a1 + m1 * p
  • x = a2 + m2 * q

可化为:

  • m1 * (-p) + m2 * q = a1 - a2

d = exgcd(m1, m2, x, y),则当且仅当 d | (a1 - a2) 时可合并,

此时 p = -x * (a1 - a2) / d,合并后的方程为

  • x ≡ a1 + m1 * p (mod LCM(m1, m2))

由于本题数据的值域较大,又计算除法时均为整除,可以先除再乘以避免 long long 溢出。

事实上如果最后的模数超出 long long 范围的话就只能用高精度了。。

Code: O(TklogV), V为值域 [696K, 16MS]

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;

int k;
ll a[100002], r[100002];

inline ll exgcd(ll a, ll b, ll &x, ll &y){
	if(!b) return x = 1, y = 0, a;
	ll d = exgcd(b, a % b, y, x);
	y -= a / b * x;
	return d;
}

int main(){
	while(scanf("%d", &k) != EOF){
		for(register int i = 1; i <= k; i++) scanf("%lld%lld", a + i, r + i);
		ll M = a[1], R = r[1], x, y, d;
		bool nosol = 0;
		for(register int i = 2; i <= k; i++){
			d = exgcd(M, a[i], x, y);
			if((R - r[i]) % d) {puts("-1"), nosol = 1; break;}
			x = (R - r[i]) / d * (-x % a[i]) % a[i];  // Divide first to avoid overflowing
			R += M * x;
			M = M / d * a[i];  // Divide first to avoid overflowing
			R %= M;
		}
		if(!nosol) printf("%lld\n", R < 0 ? R + M : R);
	}
	return 0;
}

评论

还没有任何评论,你来说两句吧



常年不在线的QQ:
49750

不定期更新的GitHub:
https://github.com/Darkleafin


OPEN AT 2017.12.10

如遇到代码不能正常显示的情况,请刷新页面。
If the code cannot be displayed normally, please refresh the page.


发现一个优美的网站:
https://visualgo.net/en
















- Theme by Qzhai