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.
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 Sample Output 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 |
[Submit] [Go Back] [Status] [Discuss]
给出来的是线性方程组, 要求解, 但是模数之间没有保证一定互质, 所以使用CRT合并
若原方程为x ≡ a1 (mod m1), x ≡ a2 (mod m2)
根据裴蜀定理若 (a2 - a1) % gcd(m1, m2) != 0 则无解
若有解使用exgcd求出一组解(p, q)
合并后的方程为x ≡ (m1 * p + a1) (mod (lcm(m1, m2) )
合并为一组, 最后的a1即是答案.
#include <algorithm>
#include <string.h>
#include <stdio.h>
#include <iostream>
using namespace std;
#define sz(a) ((int)(a).size())
typedef long long ll;
#define me(a, b) (memset(a, b, sizeof a))
const int INF = 0x3f3f3f3f;
const int MAXN = 1e5 + 10;
const ll mod = 999911659;
void exgcd(ll a, ll b, ll& x, ll& y)
{
if (b == 0)
{
x = 1;
y = 0;
return;
}
exgcd(b, a % b, x, y);
ll t = x;
x = y;
y = t - (a / b) * y;
return;
}
ll gcd(ll a, ll b)
{
return b == 0 ? a : gcd(b, a % b);
}
ll lcm(ll a, ll b)
{
return a * b / gcd(a, b);
}
int main(){
ll x, y, a1, m1, a2, m2, k;
while (cin >> k)
{
int flag = 1;
cin >> m1 >> a1;
k--;
while (k--)
{
cin >> m2 >> a2;
if (!flag)
continue;
ll d = a2 - a1;
ll u = gcd(m1, m2);
if (d % u != 0)
{
flag = 0;
continue;
}
exgcd(m1, m2, x, y);
x = x * d / u;
m2 /= u;
x = (x % m2 + m2) % m2;
a1 = m1 * x + a1;
m1 *= m2;
}
printf("%lld\n", flag == 0 ? -1 : a1);
}
return 0;
}