Strange Way to Express Integers
Time Limit: 1000MS | Memory Limit: 131072K | |
Total Submissions: 20313 | Accepted: 6858 |
Description
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.
Source
POJ Monthly--2006.07.30, Static
思路:
中国剩余定理的模板题,最近刚学~
学习博客:
https://blog.csdn.net/litble/article/details/75807726
https://blog.csdn.net/Dafang_Xu/article/details/50818919
https://blog.csdn.net/HownoneHe/article/details/52186204
代码如下:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
#define ll long long
const int N=1e+5;
ll n,m[N],a[N];
ll extgcd(ll a,ll b,ll &x,ll &y){
int d=a;
if(b!=0){
d=extgcd(b,a%b,y,x);
y-=(a/b)*x;
}
else {x=1;y=0;}
return d;
}
ll work(){
ll M=m[1],A=a[1],t,d,x,y;
for(int i=2;i<=n;i++){
d=extgcd(M,m[i],x,y);
if((a[i]-A)%d)return -1;
x*=(a[i]-A)/d;t=m[i]/d;x=(x%t+t)%t;
A=M*x+A,M=M*m[i]/d;A%=M;
}
return A=(A%M+M)%M;
}
int main(){
while(scanf("%lld",&n)!=EOF){
for(int i=1;i<=n;i++){
scanf("%d%d",&m[i],&a[i]);
}
printf("%lld\n",work());
}
}