题目链接:点击打开链接
Time Limit: 1000MS | Memory Limit: 131072K | |
Total Submissions: 14774 | Accepted: 4842 |
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
思路:
求解方程组
X%m1=r1
X%m2=r2
....
X%mn=rn
首先看下两个式子的情况
X%m1=r1
X%m2=r2
联立可得
m1*x+m2*y=r2-r1
用ex_gcd求得一个特解x'
得到X=x'*m1+r1
X的通解X'=X+k*LCM(m1,m2)
上式可化为:X'%LCM(m1,m2)=X
到此即完成了两个式子的合并,再将此式子与后边的式子合并,最后的得到的X'即为答案的通解,求最小整数解即可。
#include<cstdio>
#include<algorithm>
#include<cstring>
#define LL long long
using namespace std;
int n;
LL a1,r1,a2,r2,x,y;
LL exgcd(LL a,LL b,LL &x,LL &y)
{
if(b==0)
{
x=1;
y=0;
return a;
}
LL ans=exgcd(b,a%b,x,y);
LL t=x;
x=y;
y=t-a/b*y;
return ans;
}
int main()
{
while(~scanf("%d",&n))
{
scanf("%lld%lld",&a1,&r1);
bool flag=0;
for(int i=1;i<n;i++)
{
scanf("%lld%lld",&a2,&r2);
if(flag) continue;
LL ans=exgcd(a1,a2,x,y); // //a1*x+a2*y=gcd(a1,a2)
if((r2-r1)%ans) flag=1;
else
{
LL tp=a2/ans; // 因为: x=x0+b/gcd(a,b)*k (k=0,1,2...)
x=((r2-r1)/ans*x%tp+tp)%tp;
r1=x*a1+r1;
a1=a1/ans*a2; // 最小公倍数
r1=(r1%a1+a1)%a1;
}
}
if(flag)
puts("-1");
else
printf("%lld\n",r1);
}
return 0;
}