luogu#P3390. 【模板】矩阵快速幂
【模板】矩阵快速幂
Background
An matrix is a rectangular array of elements arranged in rows and columns. That is,
$$A = \begin{bmatrix} a_{1 1} & a_{1 2} & \cdots & a_{1 n} \\ a_{2 1} & a_{2 2} & \cdots & a_{2 n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{m 1} & a_{m 2} & \cdots & a_{m n} \end{bmatrix} \text{.}$$In this problem, the elements in a matrix are integers.
Given matrices of sizes and , respectively, their product is an matrix. Denote the result by , then
$$c_{i j} = \sum_{k = 1}^{n} a_{i k} b_{k j} \text{,\qquad($1 \le i \le m$, $1 \le j \le p$).}$$If the number of columns of does not equal the number of rows of , the product cannot be computed.
It can be verified that matrix multiplication is associative, i.e., .
An matrix can be multiplied by itself to obtain another matrix, denoted . Furthermore, higher powers can be defined recursively as , or $A^k = \underbrace{A \times A \times \cdots \times A}_{k \text{ 次}}$.
In particular, define as the identity matrix $I = \begin{bmatrix} 1 & 0 & \cdots & 0 \\ 0 & 1 & \cdots & 0 \\ \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & \cdots & 1 \end{bmatrix}$.
Problem Description
Given an matrix , compute .
Input Format
The first line contains two integers .
Then follow lines, each containing integers. In row , the -th number denotes .
Output Format
Output .
There are lines in total, each containing numbers. The number in row and column denotes . Each element is taken modulo .
2 1
1 1
1 1
1 1
1 1
3 5
1 2 3
4 5 6
7 8 9
121824 149688 177552
275886 338985 402084
429948 528282 626616
Hint
Constraints
For of the testdata, , , .
Translated by ChatGPT 5