Time Limit: 1000MS | Memory Limit: 131072K | |
Total Submissions: 14558 | Accepted: 4766 |
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
题意:找出一个数除以ai余ri,找不到输出-1
分析:看讨论有用中国剩余定理的,可是不会,上网看了没太懂,看了题解还是用扩展欧几里得,数学渣看题解都感觉好难
#include <stdio.h>
#include <string.h>
#define maxx 1123456
long long a1,a2,r1,r2,x,y,n;
long long e_gcd(long long a,long long b,long long &x,long long &y)
{
if(b==0)
{
x=1;y=0;return a;
}
long long t,tep;
t=e_gcd(b,a%b,x,y);
tep=x;
x=y;
y=tep-a/b*y;
return t;
}
void f()
{
scanf("%lld%lld",&a1,&r1);
n--;
int flag=0;
while(n--)
{
scanf("%lld%lld",&a2,&r2);
long long a=a1,b=a2,m=r2-r1; //X=a1*y1+r1 X=a2*y2+r2 a1*y1-a2*2=r2-r1
long long d=e_gcd(a,b,x,y);
// printf("%lld %lld\n",x,y);
if(m%d || flag) //如果没解,标记
{
flag=1;
continue;
}
long long l=b/d;
x=(x*(m/d)%l+l)%l; //最小整数解
r1=r1+x*a1; //通解 X‘=X+lcm(a1,a2)*k , 可以化成 X' mod lcm(a1,a2)*k = X ,X就是余数了,
//X=a1*x+r1,就是这里的r1,还是不太懂为啥通解是X‘=X+lcm(a1,a2)*k
a1=(a1*a2)/d;
}
if(flag)
{
printf("-1\n");
}
else
{
printf("%lld\n",r1);
}
}
int main()
{
while(~scanf("%lld",&n))
{
f();
}
return 0;
}