题意:
给定数组数据a1,r1,a2,r2,使得存在x,x%a1=r1,x%a2=r2,求出最小的x,没有输出-1;
扩展欧几里得的定义自己去网上搜搜,我这讲一些公式的推导。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
ll egcd(ll a,ll b,ll &x,ll &y)
{
if(b == 0)
{
x = 1 ;y = 0 ;
return a;
}
ll d=egcd(b,a%b,y,x);
y -= (a/b)*x ;
return d;
}
int main()
{
ll k,a1,a2,r1,r2,d,x,y;
while(~scanf("%lld",&k))
{
bool flag=true;
scanf("%lld%lld",&a1,&r1);
k--;
while(k--)
{
scanf("%lld%lld",&a2,&r2);
d=egcd(a1,a2,x,y);
if( (r2-r1)%d ) flag = false ;
if( flag )
{
x = (r2-r1)/d*x ;
y = a2/d ;
x = ( x%y +y)%y ;
r1 = x*a1 + r1 ;
a1 = a1*y ;
}
}
if(flag) printf("%lld\n",r1);
else printf("-1\n");
}
return 0;
}
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?
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 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.
2 8 7 11 9
31
All integers in the input and the output are non-negative and can be represented by 64-bit integral types.