luogu#P3390. 【模板】矩阵快速幂

【模板】矩阵快速幂

Background

An m×nm \times n matrix is a rectangular array of elements arranged in mm rows and nn 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 aija_{i j} in a matrix are integers.

Given matrices A,BA, B of sizes m×nm \times n and n×pn \times p, respectively, their product is an m×pm \times p matrix. Denote the result by CC, 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 AA does not equal the number of rows of BB, the product cannot be computed.

It can be verified that matrix multiplication is associative, i.e., (AB)C=A(BC)(A B) C = A (B C).

An n×nn \times n matrix AA can be multiplied by itself to obtain another n×nn \times n matrix, denoted A2=A×AA^2 = A \times A. Furthermore, higher powers can be defined recursively as Ak=A×Ak1A^k = A \times A^{k - 1}, or $A^k = \underbrace{A \times A \times \cdots \times A}_{k \text{ 次}}$.

In particular, define A0A^0 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 n×nn \times n matrix AA, compute AkA^k.

Input Format

The first line contains two integers n,kn,k.
Then follow nn lines, each containing nn integers. In row ii, the jj-th number denotes Ai,jA_{i,j}.

Output Format

Output AkA^k.

There are nn lines in total, each containing nn numbers. The number in row ii and column jj denotes (Ak)i,j(A^k)_{i,j}. Each element is taken modulo 109+710^9+7.

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 100%100\% of the testdata, 1n1001 \le n \le 100, 0k10120 \le k \le 10^{12}, Ai,j1000|A_{i,j}| \le 1000.

Translated by ChatGPT 5