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.
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 |
Time Limit: 1000MS | | Memory Limit: 131072K |
Total Submissions: 19891 | | Accepted: 6710 |
算法分析:
水题一枚,注意是不互质的中国剩余定理。
具体解释(点这里)
代码实现:
#include<iostream>
#include<string>
#include<cstdio>
using namespace std;
typedef long long ll;
ll gcd(ll a,ll b) { return b == 0 ? a : gcd(b, a % b); }
ll e_gcd (ll a, ll b, ll& x, ll& y)
{
if (b == 0)
{
x = 1, y = 0;
return a;
}
ll ans = e_gcd (b, a % b, y, x);
y -= a / b * x;
return ans;
}
ll CRT(int a[], int m[], int n)
{
ll Mi = m[1], ans = a[1];
for (int i = 2; i <= n; ++i)
{
ll mi = m[i], ai = a[i];
ll x, y;
ll gcd = e_gcd (Mi, mi, x, y);
ll c = ai - ans;
if (c % gcd != 0) return -1;
ll M = mi / gcd;
ans += Mi * ( ( (c /gcd*x) % M + M) % M);
Mi *= M;
}
if (ans == 0) //当余数都为0
{
ans = 1;
for (int i = 1; i <= n; ++i)
{
ans = ans*m[i]/gcd(ans,(ll)m[i]);
}
}
return ans;
}
int a[1005],m[1005];
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
for(int i=1;i<=n;i++)
{
scanf("%d%d",&m[i],&a[i]);
}
cout<<CRT(a,m,n)<<endl;
}
}