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 mfrom 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.
题解:
a1 *x +b1 = P-----------1
a2 * y + b2 = P------------2
1 - 2 :
a1 * x - a2 * y = b2 - b1 (得到的式子很相似A * x + B * y = K)
(A = a1 B = a2 K = b2 - b1)
看到这立马甩一套欧几里得模板上去
得到 x 的值后(令xx = x的值) P = a1 * xx + b1(a1 = lcm(a1 , a2))
然后这个式子要和第三个式子a3 * x + b3 = P
那么要给a1 赋值为lcm(a1 , a2)//a1 = a1 / k * a2//lcm(a,b)=a*b/gcd(a,b);
b1 = a1 * xx + b1;
然后继续。。。
代码:
//Full of love and hope for life
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <queue>
#include <map>
#define inf 0x3f3f3f3f
//https://paste.ubuntu.com/
//https://www.cnblogs.com/zzrturist/ //博客园
//https://blog.csdn.net/qq_44134712 //csdn
using namespace std;
typedef long long ll;
const ll N=2e5+10;
ll exgcd(ll a,ll b,ll &x,ll &y){//扩展欧几里得
if(b==0){
x=1;
y=0;
return a;
}
else{
ll t=exgcd(b,a%b,x,y);
ll g=y;
y=x-(a/b)*y;
x=g;
return t;
}
}
int main(){
ll a1,a2,b1,b2,x,y,n;
int flag;
while(cin >> n){
flag=1;
cin >> a1 >> b1;
n--;
while(n--){//原来这个叫裸的中国剩余定理不互质情况 !!!才知道
cin >> a2 >> b2;
ll A=a1;
ll B=a2;
ll m=b2-b1;
ll k=exgcd(A,B,x,y);
if(m%k!=0){
flag=0;
}
x=m/k*x;
ll h=B/k;
ll xx=(x%h+h)%h;//核心部分
b1=a1*xx+b1;//更新b1
//b1 = a1 * xx + b1;
a1=A/k*B;//更新a1
//a1 = a1 / k * a2;
//lcm(a1,a2)
}
if(flag==0){
cout << -1 << endl;
}
else{
cout << b1 << endl;
}
}
return 0;
}