题目链接: Strange Way to Express Integers
Time Limit: 1000MS Memory Limit: 131072K
Total Submissions: 17976 Accepted: 6056
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 o 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
POJ Monthly–2006.07.30, Static
题意:
给你n对ai和ri是否存在一个正整数x使每对ai和ri都满足:
x
x
ai
a
i
=
=
,求最小正解x或无解.
分析:
ex_CRT:CRT && ex_CRT.
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
typedef long long LL;
const int MAXN = 1e5 + 10;
LL a[MAXN], m[MAXN];
LL gcd(LL a, LL b) {
return b ? gcd(b, a % b) : a;
}
void ex_gcd(LL a, LL b, LL &x, LL &y) {
if(!b) {
x = 1;
y = 0;
return ;
}
ex_gcd(b, a % b, x, y);
LL tmp = x;
x = y;
y = tmp - (a / b) * y;
}
LL Inv(LL a, LL b) {
LL d = gcd(a, b);
if(d != 1) return -1;
LL x, y;
ex_gcd(a, b, x, y);
return (x % b + b) % b;
}
bool merge(LL a1, LL m1, LL a2, LL m2, LL &a3, LL &m3) {
LL d = gcd(m1, m2);
LL c = a2 - a1;
if(c % d) return false;
c = (c % m2 + m2) % m2;
m1 /= d;
m2 /= d;
c /= d;
c *= Inv(m1, m2);
c %= m2;
c *= m1 * d;
c += a1;
m3 = m1 * m2 * d;
a3 = (c % m3 + m3) % m3;
return true;
}
LL ex_CRT(LL a[], LL m[], int n) {
LL a1 = a[1];
LL m1 = m[1];
for(int i = 2; i <= n; i++) {
LL a2 = a[i];
LL m2 = m[i];
LL a3, m3;
if(!merge(a1, m1, a2, m2, a3, m3)) {
return -1;
}
a1 = a3;
m1 = m3;
}
return (a1 % m1 + m1) % m1;
}
int main() {
int n;
while(scanf("%d", &n) != EOF) {
for(int i = 1; i <= n; i++) {
scanf("%lld %lld", &m[i], &a[i]);
}
LL ans = ex_CRT(a, m, n);
printf("%lld\n", ans);
}
return 0;
}