您的位置:首页 > 其它

POJ 2891 & 2018多校练习赛(第三场)-B(扩展欧几里得解同余方程组)

2018-02-05 17:02 417 查看
Strange Way to Express Integers

Time Limit: 1000MS Memory Limit: 131072K
Total Submissions: 17888 Accepted: 6030
Description

Elina is reading a book written by Rujia Liu, which introduces a strange way to express non-negative integers. The way is described as following:

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

POJ Monthly--2006.07.30, Static
[Submit]   [Go Back]   [Status]  
[Discuss]


Home Page   

Go
Back  

To top

题意:给你k对a和r是否存在一个正整数x使每队a和r都满足:x mod a=r,求最小正解x或无解。

题解:假如几个模数互质的话我们就可以用中国剩余定理了,但是这几个m值并不一定互质。我们首先考虑两对关系

x%m1=r1       x%m2=r2;可以将其变形为:(1)x=-k1*m1+r1   (2) x=k2*m2+r2    将这两个等式联立
k1*m1+k2*m2=r1-r2;   是不是很熟悉,这不就是 ax+by=c的形式吗,是的,这道题就是求解这个方程的。

当看到这个式子的时候我们就知道要用拓展欧几里得了,我们知道当(r1-t2)不是gcd(k1,k2)的倍数时方程无解,也就是问题无解的情况。

对于当前两个式子我们可以得到新的m和r ,其实m=lcm(m1,m2),而r其实前两个方程解出的x的通解。

#include<stdio.h>
#define maxn 100005
#define ll long long
ll m[100005],r[500005],n;
void exgcd(ll a,ll b,ll &d,ll &x,ll &y)
{
if(b==0)
d=a,x=1,y=0;
else
{
exgcd(b,a%b,d,y,x);
y-=x*(a/b);
}
}
ll work()
{
ll t1=m[1],t2=r[1],x,y,d;
for(int i=2;i<=n;i++)
{
exgcd(t1,m[i],d,x,y);
if((t2-r[i])%d!=0)
return -1;
x=(t2-r[i])/d*x%m[i];
t2-=x*t1;
t1=t1/d*m[i];
t2%=t1;
}
return t2>0?t2:t2+t1;
}
int main(void)
{
while(scanf("%d",&n)!=EOF)
{
for(int i=1;i<=n;i++)
scanf("%lld %lld",&m[i],&r[i]);
printf("%lld\n",work());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: