poj2891 Strange Way to Express Integers
Time Limit: 1000MS | Memory Limit: 131072K | |
Total Submissions: 17425 | Accepted: 5863 |
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
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; typedef long long ll; ll a[1010], b[1010], n; ll gcd(ll a, ll b) { if (!b) return a; return gcd(b, a % b); } ll exgcd(ll a, ll b, ll &x, ll &y) { if (!b) { x = 1; y = 0; return a; } ll temp = exgcd(b, a % b, x, y), t = x; x = y; y = t - (a / b) * y; return temp; } ll niyuan(ll x, ll mod) { ll px, py, t; t = exgcd(x, mod, px, py); if (t != 1) return -1; return (px % mod + mod) % mod; } bool hebing(ll a1, ll n1, ll a2, ll n2, ll &a3, ll &n3) { ll d = gcd(n1, n2), c = a2 - a1; if (c % d != 0) return false; c = (c % n2 + n2) % n2; n1 /= d; n2 /= d; c /= d; c *= niyuan(n1, n2); c %= n2; //取模,在哪一个模数下就要模哪个,模数要跟着变化. c *= n1 * d; c += a1; n3 = n1 * n2 * d; a3 = (c % n3 + n3) % n3; return true; } ll China() { ll a1 = b[1], n1 = a[1], a2, n2; for (int i = 2; i <= n; i++) { ll a3, n3; a2 = b[i], n2 = a[i]; if (!hebing(a1, n1, a2, n2, a3, n3)) return -1; a1 = a3; n1 = n3; } return (a1 % n1 + n1) % n1; } int main() { scanf("%lld", &n); for (int i = 1; i <= n; i++) scanf("%lld%lld", &a[i], &b[i]); printf("%lld\n", China()); return 0; }