Time Limit: 1000MS | Memory Limit: 131072K | |
Total Submissions: 8764 | Accepted: 2650 |
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.
- 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.
题意:一个数分别被n个正整数a1,a2,a3...an除,余数分别为r1,r2,r3...rn。现在给出每组ai、ri,求最小的正整数是多少,若不存在,输出-1.
思路:输入没有保证ai之间的互质的,故不能用求逆模的方法,这里采用合并方程组的解法。
X mod m1=r1
X mod m2=r2
...
...
...
X mod mn=rn
首先,我们看两个式子的情况
X mod m1=r1……………………………………………………………(1)
X mod m2=r2……………………………………………………………(2)
则有
X=m1*k1+r1………………………………………………………………(*)
X=m2*k2+r2
那么 m1*k1+r1=m2*k2+r2
整理,得
m1*k1-m2*k2=r2-r1
这就变成了线性方程。
首先要保证GCD(m1, m2)|(r2 - r1),若不成立,则方程无解,从而方程组也无解。
否则,继续往下。
解出(k1,k2),方程的一个特解为X=k1*(r2-r1)/d%m2
于是两个方程的通解就是 X'=X+k*LCM(m1,m2)
这个式子再一变形,得 X' mod LCM(m1,m2)=X
这个方程一出来,说明我们实现了(1)(2)两个方程的合并。
令 M=LCM(m1,m2),R=r2-r1
就可将合并后的方程记为 X mod M = R。
然后,扩展到n个方程。
用合并后的方程再来和其他的方程按这样的方式进行合并,最后就能只剩下一个方程 X mod M=R,其中 M=LCM(m1,m2,...,mn)。
那么,X便是原模线性方程组的一个特解,通解为 X'=X+k*M。
AC代码:
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <queue>
#include <ctime>
#include <algorithm>
#define ll long long
using namespace std;
ll x, y;
ll ex_gcd(ll a, ll b)
{
if(!b)
{
x = 1;
y = 0;
return a;
}
ll d = ex_gcd(b, a % b);
ll t = x;
x = y;
y = t - a / b * y;
return d;
}
int main()
{
ll n, m, r;
while(cin>>n)
{
bool flag = true;
cin>>m>>r;
ll M = m, R = r;
for(int i = 1; i < n; i++)
{
cin>>m>>r;
if(!flag) continue;
ll d = ex_gcd(M, m);
if((r - R) % d)
{
flag = false;
continue;
}
x = (r - R) / d * x % m;
R += x * M;
M = M / d * m; // M=LCM(m1,m2,...,mn)
R %= M;
}
if(R <= 0) R += M;
if(flag) cout<<R<<endl;
else cout<<-1<<endl;
}
return 0;
}