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
|
[Submit] [Go Back] [Status] [Discuss]
题解:中国剩余定理,模数不互质
中国剩余定理求解同余方程要求模数两两互质,在非互质的时候其实也可以计算,这里采用的是合并方程的思想。下面是详细推导。
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<cstdio>
#define LL long long
#define N 100003
using namespace std;
int n;
LL a[N],r[N];
LL gcd(LL x,LL y)
{
LL r;
while (y) {
r=x%y;
x=y;
y=r;
}
return x;
}
void exgcd(LL a,LL b,LL &x,LL &y)
{
if (b==0) {
x=1; y=0; return;
}
exgcd(b,a%b,x,y);
LL t=y;
y=x-(a/b)*y;
x=t;
}
LL inv(LL a,LL b)
{
LL x,y;
exgcd(a,b,x,y);
return x;
}
LL merge(LL a1,LL n1,LL a2,LL n2,LL &aa,LL &rr)
{
LL c=a2-a1; LL d=gcd(n1,n2);
if (c%d) return 0;
c/=d; n1/=d; n2/=d;
LL x=inv(n1,n2);
x=(x*c)%n2;
x=x*(n1*d)+a1;
rr=n1*n2*d;
aa=(x%rr+rr)%rr;
return 1;
}
LL china()
{
LL a1,a2,n1,n2,c,d,aa,rr;
a1=a[1]; n1=r[1];
for (int i=2;i<=n;i++) {
a2=a[i]; n2=r[i];
if (!merge(a1,n1,a2,n2,aa,rr)) return -1;
a1=aa; n1=rr;
}
return (a1%n1+n1)%n1;
}
int main()
{
freopen("a.in","r",stdin);
while (scanf("%d",&n)!=EOF) {
for (int i=1;i<=n;i++) scanf("%I64d%I64d",&r[i],&a[i]);
printf("%I64d\n",china());
}
}