Topic Links:
http://poj.org/problem?id=2891
Main topic:
Select K different positive integers a1, A2 、...、 AK, for an integer m to the AI for the remainder corresponding to the integer ri, if
Select A1, A2 、...、 AK Appropriately, then the integer m can be uniquely determined by an integer pair combination (Ai,ri).
If A1, A2 、...、 AK and M are known, it is easy to determine all integer pairs (ai,ri), but the topic is known A1,
A2 、...、 AK, and all integer pairs (ai,ri), to find the corresponding nonnegative integer m values.
Ideas:
The topic can be converted to a given series of linear equations
X≡R1 (mod a1)
X≡R2 (mod a2)
x = R3 (mod a3)
......
x = RK (mod ak)
Solve X. is to solve the one-element linear congruence equations, which is solved by the extended Euclidean algorithm.
AC Code:
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring>using namespace Std;__int64 d,x,y;int n;void exgcd (__int64 a,__int64 b,__int64 &d,__int64 &x,__int64 &y) { if (!b) x = 1, y = 0, d = A; else { exgcd (b,a%b,d,y,x); Y-= x * (A/b); }} __int64 solve () { __int64 a,b,c,a1,r1,a2,r2; BOOL flag = 1; scanf ("%i64d%i64d", &a1,&r1); for (int i = 1; i < N; ++i) { scanf ("%i64d%i64d", &A2,&R2); A = a1, B = a2, c = R2-r1; EXGCD (a,b,d,x,y); if (c% d! = 0) flag = 0; int t = b/d; x = (x* (C/D)%t + t)% T; r1 = A1 * x + R1; a1 = A1 * (a2/d); } if (!flag) r1 =-1; return R1;} int main () {while (~scanf ("%d", &n)) { printf ("%i64d\n", Solve ()); } return 0;}
POJ2891 Strange-Express integers "unary linear congruence equation Group"