【数论 CRT——升级版】 poj 2891 Strange Way to Express Integers
Time Limit: 1000MS | Memory Limit: 131072K | |
Total Submissions: 25378 | Accepted: 8411 |
Description
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.
这是中国剩余定理的升级版 —— 每个mi不一定两两互质
这样就需要我们通过一下合并两两方程来解决:
如合并n%a1=b1,n%a2=b2
即a1*x+b1=a2*y+b2
a1*x-a2*y=b2-b1
设a=a1/t,b=a2/t,c=(b2-b1)/t t=gcd(a,b)
若(b2-b1)%t!=0则无解
用exgcd得到a*x+b*y=c的解x0,
通解x=x0+k*b,k为整数
带入a1*x+b1=n
a1*b*k+a1*x0+b1=n
所以b1=b1+a1*x0,a1=a1*b
//by hzwer
代码
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> using namespace std; typedef long long ll; ll gcd(ll a,ll b) { return b?gcd(b,a%b):a; } void exgcd(ll a,ll b,ll &x,ll &y) { if(!b) { x=1; y=0; return; } exgcd(b,a%b,x,y); ll t=x; x=y; y=t-(a/b)*y; } int main() { freopen("a.in","r",stdin); freopen("a.out","w",stdout); int t; while(scanf("%d",&t)!=EOF) { int flag=0,n; ll a1,a2,b1,b2; scanf("%lld%lld",&a1,&b1); for(int i=1;i<t;i++) { scanf("%lld%lld",&a2,&b2); if(flag) continue; ll a,b,c,d,x,y; a=a1,b=a2,c=b2-b1; d=gcd(a,b); if(c%d) { printf("-1\n"); flag=1; continue; } a/=d,b/=d,c/=d; exgcd(a,b,x,y); x=((c*x)%b+b)%b; b1=b1+a1*x; a1=a1*b; } if(!flag) printf("%lld\n",b1); } return 0; }