Strange Way to Express Integers
Time Limit: 1000MS | Memory Limit: 131072K |
---|
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.
Source
POJ Monthly–2006.07.30, Static
题意:取同余方程组的解。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <string>
using namespace std;
typedef unsigned long long ULL;
typedef long long LL;
typedef struct node
{
LL a;
LL b;
}Node;
Node s[11000];
int n;
LL EXGCD(LL a,LL b,LL &x,LL &y) //扩展欧几里得
{
if(b==0)
{
x = 1;
y = 0;
return a;
}
else
{
LL d = EXGCD(b,a%b,y,x);
y-=x*(a/b);
return d;
}
}
LL GCD(LL a,LL b)
{
return b==0?a:GCD(b,a%b);
}
LL LCM(LL a, LL b)
{
return a*b/GCD(a,b);
}
LL Inv(LL a,LL b)//求逆元
{
LL x,y;
LL d = EXGCD(a,b,x,y);
if(d != 1)
{
return -1;
}
else
{
return (x%b+b)%b;
}
}
bool Union(LL a1,LL b1,LL a2, LL b2,LL &a3,LL &b3)
{
LL d = GCD(a1,a2);
LL b = (b2-b1);
if(b%d) return false;
b = (b%a2+a2)%a2;
b = (b/d);
LL c = Inv(a1/d,a2/d);
b3 = b*c;
b3%=(a2/d);
b3 *=a1;
b3+=b1;
a3 = a1*a2/d;
b3 = (b3%a3+a3)%a3;
return true;
}
LL China()
{
LL aa = s[0].a,bb = s[0].b ;
for(int i = 1; i < n ; i++)
{
LL st,bt;
if(Union(aa,bb,s[i].a,s[i].b,st,bt))
{
aa = st;
bb= bt;
}
else
{
return -1;
}
}
return (bb%aa+aa%aa);
}
int main()
{
while(~scanf("%d",&n))
{
for(int i = 0 ; i < n; i++)
{
scanf("%lld %lld",&s[i].a,&s[i].b);
}
printf("%lld\n",China());
}
return 0;
}