Time Limit: 1000MS | Memory Limit: 131072K | |
Total Submissions: 14494 | Accepted: 4743 |
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.
思路:
线性同余方程组的求解,采用递归式的两两求解方法。无数论基础的自行百度该类方程的解法,内容太多,懒得写了。。。
代码:
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <iostream>
using namespace std;
typedef long long int ll;
ll ext_gcd(ll a,ll b,ll& s, ll& t){
if(b==0){
s = 1;
t = 0;
return a;
}
ll ans = ext_gcd(b,a%b,s,t);
ll tmp = s;
s = t;
t = tmp - a/b*t;
return ans;
}
int main(){
ll N;
ll m,r;
ll R,M;
ll s,t;
ll gcd;
ll i;
ll tmp;
int flag = 0;
while(~scanf("%I64d",&N)){
flag = 0;
scanf("%I64d%I64d",&M,&R);
for(i=2; i<=N; i++){
scanf("%I64d%I64d",&m,&r);
gcd = ext_gcd(M,m,s,t);
if( ((r-R)%gcd)!=0 )
flag = 1;
//这个地方一定要注意不要break出来,因为break出来,有些数据没读,被当成下一组数据的输入
//会出现TLE和RW等错误的,调了半个小时,血的教训
tmp = ((r-R)/gcd*s)%(m/gcd); //不定方程的最小解(不一定正的)
R = tmp*M+R;
M = M/gcd*m;
R = ( (R%M)+M )%M;
}
if(flag)
printf("-1\n");
else
printf("%I64d\n",R);
}
return 0;
}