This article introduces a very important topic in linear algebra—matrices (Matrix). It mainly explains the properties and operations of matrices, as well as some applications of matrix multiplication.
Vectors and Matrices
In linear algebra, vectors are divided into column vectors and row vectors.
Warning
In Taiwan, China, the translations of 「column」 and 「row」 happen to be the opposite of those used in mainland China. OI Wiki follows the convention used in mainland China and uses column and row.
The main objects studied in linear algebra are column vectors, which by convention are denoted by bold lowercase letters. In linear algebra involving many vectors and matrices, when there is no risk of confusion, the vector notation above a letter may be omitted when writing by hand.
A vector is also a special kind of matrix. To represent a row vector, write a transpose symbol at the upper right of a bold lowercase letter. Row vectors generally represent equations in linear algebra.
Introduction
Matrices arise from systems of linear equations. Like vectors, matrices embody the idea of “packing” data for processing.
For example, write the system of linear equations:
Matrices are generally represented with parentheses or square brackets. Extracting the coefficients above, write it in the form of matrix multiplication:
For short, write:
That is, left-multiply the column vector x of unknowns by a matrix A to obtain the column vector b. This equation can be regarded as the basic form of linear algebra.
The main operation model studied in linear algebra is the inner product. An inner product first multiplies and then adds; it is the process of left-multiplying a row vector by a column vector to obtain a number.
Matrix multiplication is an extension of the inner product. Matrix multiplication is equivalent to taking one row from the left matrix and one column from the right matrix, taking their inner product, and obtaining the corresponding element of the result matrix. The mnemonic is “left row, right column”.
When the object being studied is the column vector on the right, matrix multiplication amounts to left-multiplying the column vector. From the perspective of left multiplication, a matrix is a transformation of column vectors: transform every column vector of the matrix on the right in the matrix multiplication, obtaining the corresponding column vector in the result matrix.
A matrix can transform one column vector, or “pack” the transformation of a group of column vectors, and can even transform the whole space—that is, all column vectors. When a matrix is viewed as a transformation of the whole space, it is detached from the space and becomes a purely transformational object.
Definition
For a matrix , the main diagonal refers to the elements .
generally denotes the identity matrix, whose main diagonal consists of 1 and whose other positions are 0.
Matrices of the Same Type
Two matrices are called matrices of the same type if their numbers of rows and columns correspondingly agree.
Square Matrix
A matrix whose number of rows equals its number of columns is called a square matrix. A square matrix is a special kind of matrix. The customary phrase “an -order matrix” actually refers to an -order square matrix. Square matrices with the same order are matrices of the same type.
General matrices are used when studying systems of equations, vector groups, and the rank of matrices. Square matrices are used when studying eigenvalues and eigenvectors, and quadratic forms.
Main Diagonal
In a square matrix, the elements whose row and column numbers are equal form the main diagonal.
Symmetric Matrix
If the elements of a square matrix are symmetric about the main diagonal—that is, for any and , the element in row , column equals the element in row , column —then the square matrix is called a symmetric matrix.
Diagonal Matrix
A square matrix whose elements outside the main diagonal are all is called a diagonal matrix, generally written as:
The in the expression are the elements on the main diagonal.
A diagonal matrix is a symmetric matrix.
If all elements of a diagonal matrix are , it is called the identity matrix and denoted by . As long as multiplication is possible, multiplying any matrix by the identity matrix leaves it unchanged, regardless of its shape.
Triangular Matrix
If all elements below the main diagonal of a square matrix are , it is called an upper triangular matrix. If all elements above the main diagonal are , it is called a lower triangular matrix.
The product of two upper (lower) triangular matrices is still an upper (lower) triangular matrix. If all diagonal elements are not , an upper (lower) triangular matrix is invertible, and its inverse is also upper (lower) triangular.
Unit Triangular Matrix
If the diagonal of an upper triangular matrix consists entirely of s, then is called a unit upper triangular matrix. If the diagonal of a lower triangular matrix consists entirely of s, then is called a unit lower triangular matrix.
The product of two unit upper (lower) triangular matrices is still a unit upper (lower) triangular matrix, and the inverse of a unit upper (lower) triangular matrix is also a unit upper (lower) triangular matrix.
Operations
Linear Operations on Matrices
The linear operations on matrices are addition and subtraction, and scalar multiplication; all of them are performed element by element. Only matrices of the same type can be added or subtracted correspondingly.
Transpose of a Matrix
The transpose of a matrix is indicated by writing a transpose “T” symbol at the upper right of the matrix, meaning that the rows and columns of the matrix are exchanged.
A symmetric matrix remains unchanged before and after transposition.
Matrix Multiplication
Matrix multiplication is a generalization of the inner product of vectors.
The product of matrices is meaningful only when the number of columns in the first matrix equals the number of rows in the second matrix.
Let be a matrix, be an matrix, and let matrix be the product of matrix and matrix .
In matrix , the element in row , column can be written as:
In matrix multiplication, in the result matrix , the number at row , column is obtained from matrix 's row containing numbers and matrix 's column containing numbers by multiplying and then adding. Here, multiplying and then adding is the inner product of vectors. The number in row , column of the product matrix is exactly the inner product of multiplier matrix 's -th row vector and multiplier matrix 's -th column vector; the mnemonic is left row, right column.
The vectors studied in linear algebra are mostly column vectors. Based on this definition of matrix multiplication, we often study left multiplication of a column vector by a matrix. It also illustrates the idea of “packed processing”: processing the inner products of many vectors at once.
Matrix multiplication is associative, but does not generally satisfy the commutative law.
Using associativity, matrix multiplication can be optimized using the idea of binary exponentiation.
In contests, since linear recurrences can be expressed in the form of matrix multiplication, matrix binary exponentiation is also commonly used to find a term of a linearly recurrent sequence.
Optimization
First, for relatively small matrices, consider manually unrolling the loops directly to reduce the constant factor.
The loops can be reordered to improve spatial locality. This optimization does not change the time complexity of matrix multiplication, but gives a constant-factor improvement.
// Taking the reference code below as an example
mat operator*(const mat& T) const {
mat res;
for (int i = 0; i < sz; ++i)
for (int j = 0; j < sz; ++j)
for (int k = 0; k < sz; ++k) {
res.a[i][j] += mul(a[i][k], T.a[k][j]);
res.a[i][j] %= MOD;
}
return res;
}
// Rather than
mat operator*(const mat& T) const {
mat res;
int r;
for (int i = 0; i < sz; ++i)
for (int k = 0; k < sz; ++k) {
r = a[i][k];
for (int j = 0; j < sz; ++j)
res.a[i][j] += T.a[k][j] * r, res.a[i][j] %= MOD;
}
return res;
}
Inverse of a Square Matrix
For a square matrix , its inverse matrix is a matrix satisfying .
An inverse matrix does not necessarily exist. If it exists, Gaussian elimination can be used to find it.
Determinant of a Square Matrix
The determinant is an operation on a square matrix.
Reference Code
Generally, a two-dimensional array can be used to simulate a matrix.
struct mat {
LL a[sz][sz];
mat() { memset(a, 0, sizeof a); }
mat operator-(const mat& T) const {
mat res;
for (int i = 0; i < sz; ++i)
for (int j = 0; j < sz; ++j) {
res.a[i][j] = (a[i][j] - T.a[i][j]) % MOD;
}
return res;
}
mat operator+(const mat& T) const {
mat res;
for (int i = 0; i < sz; ++i)
for (int j = 0; j < sz; ++j) {
res.a[i][j] = (a[i][j] + T.a[i][j]) % MOD;
}
return res;
}
mat operator*(const mat& T) const {
mat res;
int r;
for (int i = 0; i < sz; ++i)
for (int k = 0; k < sz; ++k) {
r = a[i][k];
for (int j = 0; j < sz; ++j)
res.a[i][j] += T.a[k][j] * r, res.a[i][j] %= MOD;
}
return res;
}
mat operator^(LL x) const {
mat res, bas;
for (int i = 0; i < sz; ++i) res.a[i][i] = 1;
for (int i = 0; i < sz; ++i)
for (int j = 0; j < sz; ++j) bas.a[i][j] = a[i][j] % MOD;
while (x) {
if (x & 1) res = res * bas;
bas = bas * bas;
x >>= 1;
}
return res;
}
};
Two Perspectives on Systems of Linear Equations
There are two perspectives for viewing matrix A, or transformation A.
The first perspective is to look by rows and observe every row of A. In this way, regard A as a system of equations. This gives the process of solving equations by elimination.
The second perspective is to look by columns and observe every column of A. A itself is also composed of column vectors. This is equivalent to regarding transformation A itself as a group of column vectors, with x as the unknown coefficients, and asking whether the group of column vectors in A can be combined with the unknowns to form column vector b.
For example, the opening example becomes:
Solving the equations becomes the question of whether, by adjusting the three coefficients x, the given three basis vectors can be combined to form the resulting vector.
Looking by columns is more novel than looking by rows. From the column perspective, linear independence and linear dependence can be studied.
Applications of Matrix Multiplication
Matrix-Accelerated Recurrence
Take the Fibonacci sequence as an example. In the Fibonacci sequence, and .
If a problem asks you to find the -th term of the Fibonacci sequence, the simplest method is direct recurrence. But if the range of reaches the order of , recurrence is no longer feasible, so we can consider matrix-accelerated recurrence.
According to the matrix form of the recurrence formula for the Fibonacci sequence:
Define the initial matrix . Then is the element in row 1, column 1 of the matrix , namely the element in row 1, column 1 of .
Note
Matrix multiplication is not commutative, so you must not write the element in row 1, column 1 of . In addition, for , simply output ; there is no need to perform matrix binary exponentiation.
Why multiply by the matrix's -th power rather than the -th power? Because can be obtained without matrix multiplication. In other words, one multiplication is enough to obtain . If it is still unclear why the exponent is , try calculating it by hand.
Here is sample code for finding the -th Fibonacci number modulo (core part).
constexpr int mod = 1000000007;
struct Matrix {
int a[3][3];
Matrix() { memset(a, 0, sizeof a); }
Matrix operator*(const Matrix &b) const {
Matrix res;
for (int i = 1; i <= 2; ++i)
for (int j = 1; j <= 2; ++j)
for (int k = 1; k <= 2; ++k)
res.a[i][j] = (res.a[i][j] + a[i][k] * b.a[k][j]) % mod;
return res;
}
} ans, base;
void init() {
base.a[1][1] = base.a[1][2] = base.a[2][1] = 1;
ans.a[1][1] = ans.a[1][2] = 1;
}
void qpow(int b) {
while (b) {
if (b & 1) ans = ans * base;
base = base * base;
b >>= 1;
}
}
int main() {
int n = read();
if (n <= 2) return puts("1"), 0;
init();
qpow(n - 2);
println(ans.a[1][1] % mod);
}
This is a slightly more complicated example.
We see that is related to , so we consider constructing a matrix to describe the state.
However, if the matrix contains only the three elements , it is difficult to construct the transition equation, because exponentiation and cannot be described by a matrix.
Therefore, consider constructing a larger matrix.
We want to construct a recurrence matrix that can transition to
The transition matrix is
Matrix-Expression Updates
「THUSCH 2017」The Great Magician
The great magician Little L makes magic crystal balls, each with energy values for the water, fire, and earth attributes. Little L arranges these crystal balls in a line on the ground from front to back, and begins today's magic performance.
Let denote, respectively, the energy values of water, fire, and earth in the -th crystal ball from the front (indices start at ).
Little L plans to cast spells. Each time, he chooses an interval and casts one of the following major classes and kinds of spells:
-
Magical stimulation: the energy of a specific attribute in every crystal ball in the interval erupts, thereby enhancing the energy of another specific attribute. Specifically, there are three possible forms:
-
Fire-element stimulation of water-element energy: set .
-
Earth-element stimulation of fire-element energy: set .
-
Water-element stimulation of earth-element energy: set .
Note that enhancing the energy of one attribute does not change the energy of the other attribute; for example, does not increase or decrease .
-
-
Magical enhancement: Little L waves his staff and consumes points of his own mana to change the energy of a specific attribute in every crystal ball in the interval. Specifically, there are three possible forms:
- Fixed-value enhancement of fire-element energy: set .
- Doubling enhancement of water-element energy: set .
- Absorption and fusion of earth-element energy: set .
-
Magical release: Little L gathers the energy of all crystal balls in the interval, fuses it into a new crystal ball, and gives it to an audience member outside the performance area. The energy value of each attribute in the generated crystal ball equals the algebraic sum of the corresponding energy values of all crystal balls in the interval. Note that the magical release process does not actually change the energy of the crystal balls in the interval.
It is worth mentioning that the raw materials of the crystal balls made and fused by Little L are customized OI factory crystals, so these crystal balls have an energy threshold of . When the energy value of an attribute in a crystal ball is greater than or equal to this threshold, the energy value is automatically reduced modulo the threshold to prevent the crystal ball from exploding.
Little W is Little L's (only) audience member. He watched the entire performance and received every crystal ball fused by Little L during the performance. Little W wants to know the energy values of the three attributes contained in these crystal balls.
Because matrix multiplication satisfies associativity and distributivity, a single-point update can naturally be generalized to an interval: after deriving the matrix, maintain the product of interval matrices with a segment tree.
Here are a few examples.
The transition for
The transition for
「LibreOJ 6208」Queries on a Tree
There is a tree with nodes, rooted at node . Each node has two weights , both initially .
There are three operations:
-
operation: for every point on the path from to the root, set .
-
operation: for every point on the path from to the root, set .
-
operation: query point ; its weight is .
If considered directly, it is not easy to reason about pushing operations down and maintaining information. But matrices can express this easily.
Fixed-Length Path Statistics
Problem Statement
Given an -order directed graph whose every edge has weight , and an integer , your task is to find, for every pair of vertices , the number of paths from to of length (the path need not be simple; vertices or edges on it may be traversed multiple times).
Represent this graph with its adjacency matrix (for an edge in the graph, set and all other entries to ; if there are multiple edges, let be their number). The algorithm below also applies when the graph has self-loops.
Obviously, this adjacency matrix gives the answer for .
Suppose we know the matrix formed by the numbers of paths of length , denoted by , and want to find . The DP transition is clearly
We can view this as matrix multiplication, so the transition above can be described as
Expanding this recurrence gives
To compute this matrix power, we can use binary exponentiation, computing the result in time.
Fixed-Length Shortest Paths
Problem Statement
Given an -order weighted directed graph and an integer , find, for every pair of vertices , the length of the shortest path from to containing exactly edges. (The path need not be simple; vertices or edges on it may be traversed multiple times.)
Again construct the adjacency matrix of this graph, where represents the weight of the edge from to . If there is no edge between , then . (For multiple edges, take the minimum edge weight.)
Obviously, the matrix above gives the answer for . Again suppose we know the answer for , denoted by matrix . We now want the answer for . The transition is clearly
In fact, we can compare this with matrix multiplication: the transition above merely changes the sum of products in matrix multiplication into addition followed by taking the minimum. Thus define this operation as , namely
Thus
Expanding the recurrence gives
We can still compute the expression with matrix binary exponentiation, because it clearly satisfies associativity. The time complexity is .
Bounded-Length Path Counting/Shortest Paths
The algorithm above applies only when the number of edges is fixed. However, we can improve it to handle the case where the number of edges is at most . Specifically, consider the following problem:
Problem Statement
Given an -order directed graph with edge weights and an integer , your task is to find, for every pair of vertices , the number of paths from to whose length is at most (the path need not be simple; vertices or edges on it may be traversed multiple times).
For every vertex , create a virtual vertex to record the answer, and add the two edges and to the graph. Then, for a pair , the number of paths from to with at most edges equals the number of paths from to with exactly edges. This is because for every path with edges , there is a corresponding path with edges .
To find shortest paths with at most edges, simply add a self-loop of weight to every vertex.
Exercises
- Luogu P1962 Fibonacci Sequence, namely the example above; same problem as POJ3070
- Luogu P1349 Generalized Fibonacci Sequence, the matrix needs to be changed slightly
- Luogu P1939 Template Matrix Acceleration (Sequence), the matrix becomes a matrix; the derivation is similar to that above.
Part of this page is translated from the blog posts Кратчайшие пути фиксированной длины, количества путей фиксированной длины and its English translation Number of paths of fixed length/Shortest paths of fixed length. The Russian version is licensed under Public Domain + Leave a Link; the English version is licensed under CC-BY-SA 4.0.