Time Limit: 1000MS | Memory Limit: 131072K | |
Total Submissions: 12870 | Accepted: 4102 |
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.
题目大意:
题意就是我们要找到最小的ans%ai=ri的ans。
/*
对于w[1],w[2].....w[n]不互素的情形,就只能两个两个来求了
x=a[1] (mod m[1])
x=a[2] (mod m[2])
解完后,a=x,m=m1和m2的最小公倍数
将题目意思转化为公式:a1*x-a2*y=r2-r1,用欧几里得扩展算法求解
a1+m1*y=a2+m2*z ==> a1-a2=m2*z-m1*y
则(a1-a2)%gcd(m1,m2)=0
则:x=a2+m2*z (1)
(应该a>m,必需条件)
x=r1 (mod a1)
x=r2 (mod a2)
---> //a1*x+a2*y=gcd(a1,a2)=d
---> //r1+a1*x=r2+a2*y ---> a1*x+a2*y=r2-r1
则(r2-r1)%d!=0 不能得出
否则
{
t=a2/d;
x=((x*(r2-r1)/d)%t+t)%t//x的最小整数解
r1=x*a1+r1 //由(1)式
a1=a1*a2/d;
r1=(r1%a1+a1)%a1;
}
*/
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=10005;
typedef long long ll;
void extgcd(ll a,ll b,ll &d,ll &x,ll &y)
{
if(!b)
{
d=a;x=1;y=0;
return;
}
extgcd(b,a%b,d,y,x);
y-=x*(a/b);
}
ll crt(ll m[],ll r[],ll n)
{
ll M=m[1],R=r[1],x,y,d;
for(int i=2;i<=n;++i)
{
extgcd(M,m[i],d,x,y);
if((r[i]-R)%d)
{
return -1;
}
x=(r[i]-R)/d*x%(m[i]/d);
R+=x*M;
M=M/d*m[i];
R%=M;
}
return R>0?R:R+M;
}
int main()
{
int n;
while(~scanf("%lld",&n))
{
ll a[maxn],r[maxn];
for(ll i=1;i<=n;++i)
{
scanf("%lld%lld",&a[i],&r[i]);
}
printf("%lld\n",crt(a,r,n));
}
return 0;
}