您的位置:首页 > 其它

中国剩余定理进阶 POJ——Strange Way to Express Integers

2012-05-25 15:01 483 查看
Strange Way to Express Integers

Time Limit: 1000MSMemory Limit: 131072K
Total Submissions: 6184Accepted: 1790
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
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

这是大范围的中国剩余定理,上一篇已经介绍中国剩余定理的构造方法,这里实际上就是两个两个的九解,

直到把所有的方程用完为止,这里我只给出模板:

/*
* File:   main.cpp
* Author: hit-acm
*
* Created on 2012年5月25日, 上午12:42
*/

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define LL long long

LL GCD(LL a, LL b) {
return (b == 0) ? a : GCD(b, a % b);
}

LL extend_Euclid(LL a, LL b, LL &x, LL &y) {
if (b == 0) {
x = 1;
y = 0;
return a;
}
LL gcd = extend_Euclid(b, a % b, x, y);
LL temp = x;
x = y;
y = temp - (a / b) * x;
return gcd;
}

/*只有两个方程的式子,n % a = x && n % b = y*/
LL CRT_2(LL a, LL x, LL b, LL y) {
LL xx, yy, gcd;
gcd = extend_Euclid(a, b, xx, yy);
LL c = y - x;
while (c < 0) {
c += a;
}
if (c % gcd != 0) {
return -1;
}
xx *= c / gcd;
yy *= c / gcd;
LL t = yy / (a / gcd);
while (yy - t * (a / gcd) > 0) t++;
while (yy - (t - 1)*(a / gcd) <= 0) t--;
return (t * (a / gcd) - yy)*b + y;
}

/*中国剩余定理的主体*/

/*参数说明:crt[i][0]存的是除数,crt[i][1]存的是余数,(0<= i <n). n为方程的个数*/
LL CRT(LL crt[][2], int n) {
LL m = crt[0][0] / GCD(crt[0][0], crt[1][0]) * crt[1][0];
LL ans = CRT_2(crt[0][0], crt[0][1], crt[1][0], crt[1][1]) % m;
for (int i = 2; i < n && ans != -1; i++) {
ans = CRT_2(m, ans, crt[i][0], crt[i][1]);
m *= crt[i][0] / GCD(m, crt[i][0]);
ans %= m;
}
return ans;
}

/*如需使用最大公约数,上面函数中m即是,防止越界,可以用JAVA大数写*/
int main() {
LL crt[10001][2];
int n;
while (scanf("%d", &n) != EOF) {
for (int i = 0; i < n; i++) {
scanf("%lld%lld", &crt[i][0], &crt[i][1]);
}

/*注意这个判断*/
if (n == 1) {
printf("%lld\n", crt[0][1]);
} else {
printf("%lld\n", CRT(crt, n));
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐