Strange Way to Express Integers

Time Limit: 1000MS   Memory Limit: 131072K
Total Submissions: 19659   Accepted: 6635

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 (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.

这题坑了我好久 , 感觉思路没有问题。代码也ok,但就是Wa~~~~

好在后来看见了一个跟我风格特别特别像的代码~~~啊哈哈哈,然后A了

emmm......输出这边出了问题

题解:

a1 *x +b1 = P-----------1

a2 * y + b2 = P------------2

1 - 2 :

a1 * x - a2 * y = b2 - b1  (得到的式子很相似A * x + B * y = K)

(A = a1    B = a2   K = b2 - b1)

看到这立马甩一套欧几里得模板上去

得到 x 的值后(令xx = x的值)  P =  a1 * xx + b1(a1 = lcm(a1 , a2))

然后这个式子要和第三个式子a3 * x + b3 = P

那么要给a1 赋值为lcm(a1 , a2)

b1 = a1 * xx + b1;

然后继续。。。。。。

代码:

#include <stdio.h>
#include <iostream>
#include <string>
#include <cstring>
#define ll long long
using namespace std;
ll ExEuclid(ll a , ll b , ll &x , ll &y)
{
	if(b == 0)
	{
		x = 1;y = 0;
		return a;
	}
	ll tx , ty;
	ll d = ExEuclid(b , a%b , tx , ty);
	x = ty;
	y = tx - (a/b)*ty;
	return d ;
}
int main()
{
	ll t , a1 , b1 , a2 , b2 , x ,y;
	ll A , B , K;
	int flag;
	while(~scanf("%lld" , &t))
	{
		flag = 0;
		t--;
		scanf("%lld %lld" , &a1 , &b1);
		while(t--)
		{
			scanf("%lld %lld" , &a2 , &b2);
			A = a1 ; B = a2;  K = b2-b1;
			ll d = ExEuclid(A , B ,x , y);
			if(K % d != 0) 
			{
				flag = 1;
			}
		
				x = K / d * x;
				ll t = B / d;
				ll xx = (x % t + t) % t;
				b1 = a1 * xx + b1;
				a1 = A / d * B;
				
		}
		if(flag == 1)
		{
			printf("-1\n");
		 } 
		 else
		 {
		 	printf("%lld\n" , b1);
		 }
	
	}
	
	return 0;
 }