矩阵应用学习笔记

· · 算法·理论

矩阵应用学习笔记

矩阵的定义

由 m\times n 个数 a_{ij} 排成的 m 行 n 列的数表称为 m 行 n 列的矩阵,记作:

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}

矩阵的运算

矩阵的加减法

加减法要求两个矩阵为同型矩阵,即行、列数相同。

\begin{bmatrix} 1 & 4 & 2 \\ 2 & 0 & 0 \end{bmatrix} + \begin{bmatrix} 0 & 0 & 5 \\ 7 & 5 & 0 \end{bmatrix}=\begin{bmatrix} 1+0 & 4+0 & 2+5 \\ 2+7 & 0+5 & 0+0 \end{bmatrix}=\begin{bmatrix} 1 & 4 & 7 \\ 9 & 5 & 0 \end{bmatrix}

矩阵的乘法

两个矩阵 A 和 B 相乘要求 A 的列数和 B 的行数相同,设 A 的大小为 m\times n,B 的大小为 n\times q,乘积 C=AB 的大小为 m\times q,计算公式为:

c_{ij}=\sum_{k=1}^n a_{ik} \times b_{kj} \begin{bmatrix} 1 & 0 & 2 \\ -1 & 3 & 1 \end{bmatrix} \times \begin{bmatrix} 3 & 1 \\ 2 & 1 \\ 1 & 0 \end{bmatrix} = \begin{bmatrix} 1\times 3 + 0\times 2+2\times1 & 1\times 1+0\times 1+2\times 0 \\ -1\times3+3\times2+1\times1 & -1\times1+3\times1+1\times 0 \end{bmatrix} =\begin{bmatrix} 5 & 1 \\ 4 & 2\end{bmatrix}

矩阵快速幂

一个大小为 n \times n 的矩阵 A 可以与自身进行乘法,得到的仍是大小为 n \times n 的矩阵,任意高次方 A^k = A \times A^{k - 1}。

模板 P3390

struct matrix{
    ll m[N][N];
}a;
matrix operator * (const matrix &a, const matrix &b){
    matrix c;
    memset(c.m, 0, sizeof(c.m));
    for(int i = 1; i <= n; i++){
        for(int j = 1; j <= n; j++){
            for(int k = 1; k <= n; k++){
                c.m[i][j] = (c.m[i][j] + a.m[i][k] * b.m[k][j] % p) % p; 
            } 
        }
    }
    return c;
}
matrix qpow(matrix a, ll b){
    matrix ans;
    memset(ans.m, 0, sizeof(ans.m));

    for(int i = 1; i <= n; i++){
        ans.m[i][i] = 1;
    } 
    while(b){
        if(b&1) ans = ans * a;
        a = a * a;
        b >>= 1;
    }
    return ans;
}

矩阵快速幂加速线性递推

当递推数列 F_0,F_1,F_2\cdots F_n 递推公式为线性的,可以使用矩阵快速幂加速递推。

斐波那契数列

递推式:F(n)=F(n-1)+F(n-2),F(1)=F(2)=1。
构造矩阵

S_n=\begin{bmatrix} F(n) \\ F(n-1) \end{bmatrix}

下面一个表格,展示了递推式的转移: | | F(n-1) | F(n-2) | |:------:|:------:|:------:| | F(n) | 1 | 1 | | F(n-1) | 1 | 0 |

得出单位矩阵 T = \begin{bmatrix}1 & 1 \\1 & 0 \\\end{bmatrix}

\begin{bmatrix} F(n) \\ F(n-1) \end{bmatrix}=\begin{bmatrix}1 & 1 \\1 & 0 \\\end{bmatrix} \cdot \begin{bmatrix} F(n-1) \\ F(n-2) \end{bmatrix}

则最终 S_n=T^{n-2}\cdot S_2

模板 P1962

struct matrix{
    ll m[N][N];
}ans, base;
void init(){
    base.m[1][1] = base.m[1][2] = base.m[2][1] = 1;
    ans.m[1][1] = ans.m[2][1] = 1;
}
matrix operator * (const matrix &a, const matrix &b){
    matrix c;
    memset(c.m, 0, sizeof(c.m));
    for(int i = 1; i <= 2; i++){
        for(int j = 1; j <= 2; j++){
            for(int k = 1; k <= 2; k++){
                c.m[i][j] = (c.m[i][j] + a.m[i][k] * b.m[k][j] % p) % p; 
            } 
        }
    }
    return c;
}
matrix qpow(matrix a, ll b){
    while(b){
        if(b&1) ans = a * ans;
        a = a * a;
        b >>= 1;
    }
    return ans;
}