Time Limit: 1000MS | Memory Limit: 131072K | |
Total Submissions: 14804 | Accepted: 4856 |
Description
Choose k different positive integers a1, a2,…, ak. For some non-negative m, divide it by everyai (1 ≤ i ≤ k) to find the remainder ri. Ifa1, 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 findm 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.
X mod m1=r1
X mod m2=r2
...
X mod mn=rn
可以转换
X % m1=r1
X % m2=r2
则有
X = m1*k1+r1
X = m2*k2+r2
那么 m1*k1+r1 = m2*k2+r2
整理,得
m1*k1-m2*k2 = r2-r1
原式变成ax+by = m的形式
用ex_gcd求得一个特解x'
得到X = x'*m1+r2
X的通解X' = X+k*LCM(m1,m2)
求X'的最小整数解,另X'为0,根据X+k*LCM(m1,m2) = 0可以求得k = X/LCM(m1,m2)(参考扩展欧几里得原理那一篇)
再将k代入原式得X-k*LCM(m1,m2)=0,因为计算机计算原理,k经过舍去小数部分的运算过程,所以得出一个近似于0的数,若结果小于0,再加上一个X/LCM(m1,m2)即可得到最小整数解
或者更为简便,求X'最小整数解,即求X-k*LCM(m1,m2)的最小整数解,可见整个式子只和LCM(m1,m2)有关,直接对LCM(m1,m2)取余,得到X%LCM(m1,m2),为防止结果小于0,再加上一个LCM(m1,m2)并对其取余即可(具体见代码)
再将此式子与后边的式子合并,最后的得到的X'即为答案的通解,求最小整数解即可
#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<set>
#include<queue>
#include<vector>
#include<functional>
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define CL(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long LL;
const int maxn = 1e5+10;
const int MOD = 1e9+7;
void ex_gcd(LL a, LL b, LL& d, LL& x, LL& y){
if(!b){
d = a;
x = 1;
y = 0;
}
else{
ex_gcd(b, a%b, d, y, x);
y -= x*(a/b);
}
}
int main(){
LL d, x, y, m1, m2, n1, n2;
int t;
while(scanf("%d", &t) == 1){
bool flag = false;
scanf("%lld%lld", &m1, &n1);
t--;
while(t--){
scanf("%lld%lld", &m2, &n2);
if(flag) continue;
ex_gcd(m1, m2, d, x, y);
LL c, t, k;
c = n2-n1;
if(c % d) flag = true;
else{
c /= d;
t = m2/d;
x *= c;
k = (x%t+t)%t;//此处求x的最小整数解,与求X'是一样的
/*k = x*d/m2;
k = x-k*m2/d;
if(k < 0) k += m2/d;*/
n1 += m1*k;//求X,即将得到的x的特解带入原式
m1 = m1/d*m2;//求lcm(m1,m2)
n1 = (n1%m1+m1)%m1;//求X'最小整数解,取余运算
}
}
printf("%lld\n", flag ? -1 : n1);
}
return 0;
}