Problem description: a matrix of N * n and a positive integer k are given, requesting S = a + A ^ 2 + A ^ 3 + A ^ 4 +... + A ^ K value. A ^ X indicates the result of X a ry.
About input: the input contains a set of data.
The first line is three positive integers n k m, (n <= 30, k <= 1000000000, m <= 10000 ).
The next n rows, N numbers in each row, represent this matrix.
About output: the value of output matrix s after M modulo, including N rows, N numbers per line
Example input:
2 2 4
0 1
1 1
Example output:
1 2
2 3
Solution:Order B = [
[A]
[0 I]
]
Then B ^ K = [
[A ^ K a... a ^ K]
[0 I]
]
Then, the K power of matrix B has a limit, that is, the answer.
Code:
# Include <iostream> # define max_size 30 using namespace STD; int N, K, M; /* ===================================================== =================== define the matrix structure matrix; and reload operators + and *. ========================================================== =============== */struct matrix {int Val [max_size] [max_size]; matrix Operator + (const Matrix & L) {matrix temp; For (INT I = 0; I <n; I ++) for (Int J = 0; j <N; j ++) temp. val [I] [J] = (Val [I] [J] + L. val [I] [J]) % m; return temp;} Matrix Operator * (const Matrix & L) {matrix temp; For (INT I = 0; I <N; I ++) {for (Int J = 0; j <n; j ++) {temp. val [I] [J] = 0; For (int K = 0; k <n; k ++) temp. val [I] [J] = (temp. val [I] [J] + val [I] [k] * L. val [k] [J]) % m ;}return temp ;}} A, S; /* ===================================================== =================== use the division and conquer method to the K power of the matrix; l is the input matrix, and K is the k power. ========================================================== ================= */matrix power (matrix L, int K) {matrix temp; If (k = 1) return l; temp = L * l; If (K & 1) return power (temp, (k-1)/2) * l; else return power (temp, K/2 );} /* ===================================================== ==================== sum by the Division and Control Law; l is the input matrix; K is the k POWER ====================================== =============================== */matrix sum (int K) {matrix temp, tpow; If (k = 1) return a; temp = sum (K/2); If (K & 1) {tpow = power (, k/2 + 1); temp = temp + temp * tpow + tpow;} else {temp = temp + power (A, K/2) * temp;} return temp ;} int main () {// enter the scanf parameter of array A ("% d", & N, & K, & M ); // Several intermediate variables used for calculation and the matrix for (INT I = 0; I <n; I ++) {for (Int J = 0; j <N; j ++) {scanf ("% d", &. val [I] [J]) ;}// calculates the sum of squares of the matrix S = sum (k); // outputs the array element for (INT I = 0; I <N; I ++) {for (Int J = 0; j <n-1; j ++) {printf ("% d", S. val [I] [J]);} printf ("% d/N", S. val [I] [n-1]);} system ("pause"); Return 0 ;}