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.
裸的中国剩余定理不互质情况的模板套用
不太懂的可以看我的这篇博客
中国剩余定理算法详解(互质与不互质情况)
code:
#include
#include
#include
using namespace std;
typedef long long ll;
const int maxn = 1e5+10;
bool flag;
ll m[maxn],a[maxn];
ll gcd(ll a,ll b){
return b ? gcd(b,a%b) : a;
}
ll ex_gcd(ll a,ll b,ll &x,ll &y){
if(!b){
x = 1;
y = 0;
return a;
}
ll g = ex_gcd(b,a%b,y,x);
y -= a / b * x;
return g;
}
ll China(int n){
ll m1 = m[0],a1 = a[0];
ll m2,a2,k1,k2,x0,g,c;
ll lcm = m[0];
for(int i = 1; i < n; i++){
m2 = m[i];
a2 = a[i];
c = a2 - a1;
g = ex_gcd(m1,m2,k1,k2);
lcm = lcm * m[i] / gcd(lcm,m[i]);
if(c % g){
flag = false;
return 0;
}
x0 = k1 * c / g;
ll t = m2 / g;
x0 = (x0 % t + t) % t;
a1 += m1 * x0;
m1 = m2 / g * m1;
}
return a1;
}
int main(){
int k;
while(~scanf("%d",&k)){
flag = true;
for(int i = 0; i < k; i++){
scanf("%lld%lld",&m[i],&a[i]);
}
ll ans = China(k);
if(!flag)
printf("-1\n");
else
printf("%lld\n",ans);
}
return 0;
}