POJ 2891 Strange Way to Express Integers

来源:互联网 发布:十大网络推广公司排名 编辑:程序博客网 时间:2024/06/14 01:49
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.
Source

POJ Monthly--2006.07.30, Static


普通的中国剩余定理要求所有的互素,那么如果不互素呢,怎么求解同余方程组?

 

这种情况就采用两两合并的思想,假设要合并如下两个方程

 

      

 

那么得到

 

       

 

在利用扩展欧几里得算法解出的最小正整数解,再带入

 

       

 

得到后合并为一个方程的结果为

 

       

 

这样一直合并下去,最终可以求得同余方程组的解。

#include<iostream>#include<cstring>#include<cstdio>#include<cmath>using namespace std;#define LL long long#define MAXN 1005LL a[MAXN],m[MAXN];LL gcd(LL a,LL b){ return b==0 ? a : gcd(b,a%b); }void EX_GCD(LL a,LL b,LL &x, LL &y){if(!b){x=1;y=0;return ; }EX_GCD(b,a%b,x,y);LL tmp=x; x = y;y=tmp-(a/b)*y;}LL Inv(LL a,LL b){LL d=gcd(a,b);if(d!=1) return -1;LL x,y;EX_GCD(a,b,x,y);return (x%b+b)%b;}bool Megre(LL a1,LL m1,LL a2,LL m2,LL &a3,LL &m3){LL d=gcd(m1,m2),c=a2-a1;if(c % d) return false;c=(c%m2+m2)%m2;m1/=d; m2/=d; c/=d;c *= Inv(m1,m2);c%=m2; c*= m1*d;c+=a1; m3=m1*m2*d;a3=(c%m3 + m3)%m3;return true;}LL CRT(LL a[],LL m[],int n){LL a1=a[1],m1=m[1];for(int i=2;i<=n;i++){LL a2=a[i],m2=m[i];LL a3,m3;if(!Megre(a1,m1,a2,m2,a3,m3)) return -1;a1=a3; m1=m3;}return (a1%m1 + m1) % m1;}int main(){int n;while(scanf("%d",&n)!=EOF){for(int i=1;i<=n;i++)scanf("%lld%lld",&m[i],&a[i]);LL ans=CRT(a,m,n);printf("%I64d\n",ans);}return 0;}

题解来自:CSDN  ACdreamer
原创粉丝点击