点击打开题目
Strange Way to Express Integers
Time Limit: 1000MS | Memory Limit: 131072K | |
---|---|---|
Total Submissions: 13816 | Accepted: 4450 |
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.
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
给的数不一定互素,所以应该合并方程,这里把方程全部合并为 x % m [ 1 ] = a [ 1 ]
具体合并的说明看这篇博客:点击打开链接
代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define CLR(a,b) memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
#define MAX 10000
__int64 a[MAX+11];
__int64 m[MAX+11];
__int64 GCD(__int64 a , __int64 b)
{
return b == 0 ? a : GCD(b,a%b);
}
__int64 exGCD(__int64 a,__int64 b,__int64 &x,__int64 &y)
{
if (!b)
{
x = 1;
y = 0;
return a;
}
int g = exGCD(b,a%b,y,x);
y -= a / b * x;
return g;
}
__int64 CRT(__int64 *m,__int64 *a,int n) //x % m == a
{
__int64 lcm = 1;
for (int i = 1 ; i <= n ; i++)
lcm = m[i] / GCD(m[i],lcm) * lcm;
for (int i = 2 ; i <= n ; i++)
{
__int64 A = m[1] , B = m[i],d,x,y,c = a[i] - a[1]; //d 为 GCD(A,B)
d = exGCD(A,B,x,y);
if (c % d != 0) //无解
return -1;
__int64 mod = m[i] / d;
//然后套公式
__int64 K = ((x * c / d) % mod + mod) % mod;
a[1] = m[1] * K + a[1];
m[1] = m[1] * m[i] / d;
}
if (a[1] == 0) //如果最后合并的结果的余数为0,答案就是他们的最小公倍数
return lcm;
return a[1];
}
int main()
{
int n;
while (~scanf ("%d",&n))
{
for (int i = 1 ; i <= n ; i++)
scanf ("%I64d %I64d",&m[i],&a[i]);
__int64 ans = CRT(m,a,n);
printf ("%I64d\n",ans);
}
return 0;
}