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

猜你喜欢

转载自blog.csdn.net/forever_dreams/article/details/88621413