「POJ2891」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
1 2 3 |
2 8 7 11 9 |
Sample Output
1 |
31 |
Hint
All integers in the input and the output are non-negative and can be represented by 64-bit integral types.
题解
此题要求求n个同余方程的解,有多组测试数据
ai不互质
用exgcd将俩个同余方程合并成一个
如合并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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
#include<cstdio> #include<iostream> #define ll long long using namespace std; inline ll read() { ll x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x*=10;x+=ch-'0';ch=getchar();} return x*f; } int k; ll a1,b1,a2,b2; bool flag; inline ll gcd(ll a,ll b){return b==0?a:gcd(b,a%b);} 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=x;x=y;y=t-a/b*y; } int main() { while(cin>>k) { flag=0; a1=read();b1=read(); ll a,b,c,x,y; for(int i=1;i<k;i++) { a2=read();b2=read(); if(flag)continue; a=a1;b=a2;c=b2-b1; ll t=gcd(a,b); if(c%t){printf("-1\n");flag=1;} else { a/=t;b/=t;c/=t; 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; } |