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

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 a1a2…, ak. For some non-negative m, divide it by every ai (1 ≤ i ≤ k) to find the remainder ri. If a1a2, …, ak are properly chosen, m can be determined, then the pairs (airi) 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 airi (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

[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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值