Time Limit: 1000MS | Memory Limit: 131072K | |
Total Submissions: 11750 | Accepted: 3661 |
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.
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.
题意:给你n个方程组
x % m[0] = a[0]
x % m[1] = a[1]
...
x % m[n-1] = a[n-1]
让你求x 的值,不存在输出-1。
CRT——exgcd合并方程组
#include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #define LL long long #define MAXN 10100 using namespace std; LL gcd(LL a, LL b){ return b == 0 ? a : gcd(b, a%b); } void exgcd(LL a, LL b, LL &d, LL &x, LL &y) { if(!b){d = a, x = 1, y = 0;} else { exgcd(b, a%b, d, y, x); y -= x * (a / b); } } LL CRT(LL l, LL r, LL *m, LL *a) { LL lcm = 1; for(LL i = l; i <= r; i++) lcm = lcm / gcd(lcm, m[i]) * m[i]; for(LL i = l+1; i <= r; i++) { LL A = m[l], B = m[i], d, x, y, c = a[i] - a[l]; exgcd(A, B, d, x, y); if(c % d) return -1; LL mod = m[i] / d; LL k = ((x * c / d) % mod + mod) % mod; a[l] = m[l] * k + a[l]; m[l] = m[l] * m[i] / d; } if(a[l] == 0) return lcm; return a[l]; } LL a[MAXN], m[MAXN], n; int main() { while(scanf("%lld", &n) != EOF) { for(LL i = 0; i < n; i++) scanf("%lld%lld", &m[i], &a[i]); printf("%lld\n", CRT(0, n-1, m, a)); } return 0; }