| Time Limit: 1000MS | Memory Limit: 131072K | |
| Total Submissions: 9042 | Accepted: 2741 |
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.
Source
//356K 16MS
#include<stdio.h>
long long a,b,c,a1,a2,r1,r2,x,y,k;
long long exgcd(long long A,long long &x,long long B,long long &y)
{
long long x1,y1,x0,y0;
x0=1;
y0=0;
x1=0;
y1=1;
long long r=(A%B+B)%B;
long long q=(A-r)/B;
x=0;
y=1;
while(r)
{
x=x0-q*x1;
y=y0-q*y1;
x0=x1;
y0=y1;
x1=x;
y1=y;
A=B;
B=r;
r=A%B;
q=(A-r)/B;
}
return B;
}
long long solve()
{
bool flag=1;
scanf("%I64d%I64d",&a1,&r1);
for(long long i=1; i<k; i++)
{
scanf("%I64d%I64d",&a2,&r2);
a=a1;
b=a2;
c=r2-r1;
long long d=exgcd(a,x,b,y);
if(c%d!=0)
{
flag=0;
}
long long t=b/d;
x=(x*(c/d)%t+t)%t;
r1=a1*x+r1;
a1=a1*(a2/d);
}
if(!flag)return -1;
return r1;
}
int main()
{
while(scanf("%I64d",&k)!=EOF)
{
printf("%lld\n",solve());
}
return 0;
}
本文介绍了解决一元线性同余方程组问题的方法,通过给出的算法实现,能够从一系列模数对求解出对应的最小非负整数解。适用于编程竞赛等场景。
468

被折叠的 条评论
为什么被折叠?



