微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

【POJ 2891】Strange Way to Express Integers

【题目】

传送门

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.


【分析】

这是一道 exCRT 的模板题。

具体的做法就看我的另一篇博客中国剩余定理


代码

#include<cstdio>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
void exgcd(ll a,ll b,ll &x,ll &y)
{
	if(!b)  {x=1,y=0;return;}
	exgcd(b,a%b,y,x),y-=a/b*x;
}
int main()
{
	int n,i;
	while(~scanf("%d",&n))
	{
		ll m1,a1,m2,a2,x,y;
		scanf("%lld%lld",&m1,&a1);
		bool flag=true;
		for(i=2;i<=n;++i)
		{
			scanf("%lld%lld",&m2,&a2);
			ll Gcd=__gcd(m1,m2),Lcm=m1*m2/Gcd,A=a2-a1;
			if(A%Gcd)  {flag=false;continue;}
			m1/=Gcd,m2/=Gcd,A/=Gcd;
			exgcd(m1,m2,x,y),x=(x*A%m2+m2)%m2;
			a1+=m1*Gcd*x,m1=Lcm;
		}
		printf("%lld\n",flag?a1:-1);
	}
	return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐