Hdu_1588
Assume that F is the same matrix containing the Fibonacci items, and the final result is the matrix S (n-1) = f ^ (B) + f ^ (K + B) +... + F ^ (K * (n-1) + B) elements in the upper left corner.
For the matrix S and F, the recursive formula S (n) = S (n-1) + f ^ (K * n + B), f ^ (K * (n + 1) can be obtained) + B) = a ^ (k) * f ^ (K * n + B). matrix A is the matrix shown in. Therefore, we can construct the two Recursive formulas into a matrix of Recursive Relations, and then use the binary matrix method to quickly obtain S (n-1.
# Include <stdio. h> # Include < String . H> # Define Maxd 8 Int K, B, n, m; Struct Matrix { Int A [maxd] [maxd]; matrix () {memset (, 0 , Sizeof (A) ;}}; matrix multiply (Matrix & X, Matrix & Y ){ Int I, J, K; Matrix Z; For (K = 0 ; K < 8 ; K ++ ) For (I = 0 ; I < 8 ; I ++ ) If (X. A [I] [k]) { For (J = 0 ; J < 8 ; J ++ ) If (Y. A [k] [J]) Z. A [I] [J] = (Z. A [I] [J] + ( Long Long ) X. A [I] [k] * Y. A [k] [J]) % M ;} Return Z;} matrix powmod (Matrix & Unit, Matrix & mat, Int N ){ While (N ){ If (N & 1 ) Unit = Multiply (MAT, Unit); n >>= 1 ; MAT = Multiply (MAT, mat );} Return Unit;} matrix getf ( Int N) {matrix unit, mat; Unit. [ 0 ] [ 0 ] = 1 ; Mat. [ 0 ] [ 0 ] = Mat. [ 0 ] [ 1 ] = Mat. [1 ] [ 0 ] = 1 ; Powmod (unit, mat, n - 1 ); Return Unit;} matrix geta ( Int N) {matrix unit, mat; Unit. [ 0 ] [ 0 ] = Unit. [ 1 ] [ 1 ] =1 ; Mat. [ 0 ] [ 0 ] = Mat. [ 0 ] [ 1 ] = Mat. [ 1 ] [ 0 ] = 1 ; Unit = Powmod (unit, mat, N ); Return Unit ;} Void Solve (){ Int I, J; matrix unit, mat, AK, AB, AKB; If (B) {AB = Getf (B ); For (I = 0 ; I < 4 ; I ++ ) For (J = 0 ; J < 4 ; J ++ ) Unit. A [I] [J] =AB. A [I] [J];} If (K + B) {AKB = Getf (B + K ); For (I = 0 ; I < 4 ; I ++ ) For (J = 0 ; J < 4 ; J ++ ) Unit. A [I + 4 ] [J] =AKB. A [I] [J];} For (I = 0 ; I < 4 ; I ++ ) Mat. A [I] [I] = Mat. A [I] [I + 4 ] = 1 ; AK = Geta (k ); For (I = 0 ; I < 4 ; I ++ ) For (J = 0 ; J < 4 ; J ++ ) Mat. A [I + 4 ] [J + 4 ] = AK. A [I] [J]; Unit = Powmod (unit, mat, N- 1 ); Printf ( " % D \ n " , Unit. [ 0 ] [ 0 ]);} Int Main (){ While (Scanf ( " % D " , & K, & B, & N, & M) = 4 ) {Solve ();} Return 0 ;}