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
|
中国剩余定理:
#include<stdio.h>
#include<algorithm>
#include<string.h>
#define ll __int64
ll gcd(ll a,ll b,ll &x,ll &y)
{
if(b==0)
{
x=1;
y=0;
return a;
}
ll d=gcd(b,a%b,x,y);
ll t=x;
x=y;
y=t-a/b*y;
return d;
}
ll mod(ll a,ll b ,ll n,ll &d)
{
ll e,x,y;
d=gcd(a,n,x,y);
if(b%d!=0)
return -1;
e=(x*(b/d))%n;
while(e<0)
e+=n/d;
return e;
}
int main()
{
bool flag;
ll m,r1,a1,a2,r2,x,d;
while(~scanf("%I64d",&m))
{
scanf("%I64d%I64d",&a1,&r1);
flag=0;
for(int i=1;i<m;i++)
{
scanf("%I64d%I64d",&a2,&r2);
if(flag)
continue;
x=mod(a1,r2-r1,a2,d);
if(x==-1)
{
flag=1;
continue;
}
r1+=a1*x;
a1=a1*a2/d;
r1=(r1%a1+a1)%a1;
}
if(flag)
printf("-1\n");
else
printf("%I64d\n",r1);
}
}