Poj 2891 Strange Way to Express Integers【crt】

Strange Way to Express Integers
Time Limit: 1000MS   Memory Limit: 131072K
Total Submissions: 12923   Accepted: 4126

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

POJ Monthly--2006.07.30, Static


题意:

题目说的是,给出若干组除数和余数,求能确定满足所有组的最小的数,如果不存在,输出-1


题解:

中国剩余定理,不是特别懂,无解的情况是基于拓展欧几里得...

/*
http://blog.csdn.net/liuke19950717
*/

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const ll maxn=5005;
void extgcd(ll a,ll b,ll &d,ll &x,ll &y)
{
	if(!b)
	{
		d=a;x=1;y=0;
		return;
	}
	extgcd(b,a%b,d,y,x);
	y-=(a/b)*x;
}
ll crt(ll n,ll a[],ll r[])
{
	ll M=a[0],R=r[0],x,y,d;
	for(int i=1;i<n;++i)
	{
		extgcd(M,a[i],d,x,y);
		if((r[i]-R)%d)
		{
			return -1;
		}
		x=(r[i]-R)/d*x%(a[i]/d);
		R+=x*M;
		M=M/d*a[i];
		R%=M;
	}
	return R>0?R:R+M;
}
int main()
{
	ll n;
	while(~scanf("%lld",&n))
	{
		ll a[maxn]={0},r[maxn]={0};
		for(ll i=0;i<n;++i)
		{
			scanf("%lld%lld",&a[i],&r[i]);
		}
		printf("%lld\n",crt(n,a,r));
	}
	return 0;
} 




你可能感兴趣的:(Poj 2891 Strange Way to Express Integers【crt】)