目录
POJ - 2891 Strange Way to Express Integers
一,剩余定理
二,OJ实战
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.
代码:
-
#include <iostream>
-
using
namespace
std;
-
#define l long long
-
-
l x, y;
-
-
l gcd(l a, l b)
-
{
-
if (a ==
0 || b ==
0)
-
{
-
x = (b ==
0);
-
y = (a ==
0);
-
return a + b;
-
}
-
l r;
-
if (a <
0)
-
{
-
r = gcd(-a, b);
-
x *=
-1;
-
return r;
-
}
-
if (b <
0)
-
{
-
r = gcd(a, -b);
-
y *=
-1;
-
return r;
-
}
-
if (a >= b)r = gcd(a%b, b);
-
else r = gcd(a, b%a);
-
y -= a / b*x;
-
x -= b / a*y;
-
return r;
-
}
-
-
l cheng(l a, l b, l p)
-
{
-
if (b ==
0)
return
0;
-
if (b <
0)
return cheng(a, -b, p)*
-1;
-
l c = cheng(a, b /
2, p);
-
c = c + c;
-
if (b %
2)c += a;
-
return c%p;
-
}
-
-
int main()
-
{
-
l t, a1, r1, a2, r2;
-
while (
cin >> t)
-
{
-
a1 =
1, r1 =
0;
-
while (t--)
-
{
-
cin >> a2 >> r2;
-
if (r1 >=
0)
-
{
-
l g = gcd(a1, a2);
-
if ((r2 - r1) % g)r1 =
-1;
-
else
-
{
-
l a3 = a1 / g*a2;
-
r1 += cheng(cheng((r2 - r1) / g, x, a3), a1, a3);
-
r1 = (r1%a3 + a3) % a3;
-
a1 = a3;
-
}
-
}
-
}
-
cout << r1 <<
endl;
-
}
-
return
0;
-
}
转载:https://blog.csdn.net/nameofcsdn/article/details/115763188