矩阵快速幂与线性递推加速
从斐波那契第 10^18 项算不动讲起,用大白话讲透矩阵乘法与转移矩阵的 3 步构造法,并带你掌握定长路径计数与 min-plus 广义矩阵乘法。
先看一个问题:为什么需要它?
大家都很熟悉斐波那契数列:0, 1, 1, 2, 3, 5, 8, 13, ...,规则是 ,从第 项开始每一项等于前两项之和()。
如果题目问你第 项 是多少,写一个 for 循环从 跑到 ,不到 微秒就算出来了。
但如果题目突然把数据范围改成 ,要求算出 呢? 就算计算机每秒能跑 次循环,跑 次也需要 秒——整整 300 多年!
矩阵快速幂就是专治这种“步数高达 、但每一步规则固定”的递推难题。它的核心点子用大白话讲就是:
普通的
for循环是一步一步往前挪;矩阵快速幂则是把“往前走一步的规则”打包成一张固定不变的乘法表(转移矩阵 ),再借用快速幂的“倍增魔法”(一次跨 步、 步、 步……),只需要 次矩阵乘法,就能瞬间跳到第 项!
核心思想:用人话讲明白原理
1. 1 分钟看懂矩阵乘法与结合律
没学过线性代数也不用慌,把一个 矩阵看成一张“ 行 列的数字方格表”就行。矩阵乘法只有一条规则:左边挑第 横行,右边挑第 竖列,对应位置相乘再相加,填进结果表的第 行第 列。
拿两个具体的小方阵算一次:
$$\begin{pmatrix} 1 & 1 \\ 1 & 0 \end{pmatrix} \times \begin{pmatrix} 2 & 1 \\ 1 & 1 \end{pmatrix} = \begin{pmatrix} 1\times 2 + 1\times 1 & 1\times 1 + 1\times 1 \\ 1\times 2 + 0\times 1 & 1\times 1 + 0\times 1 \end{pmatrix} = \begin{pmatrix} 3 & 2 \\ 2 & 1 \end{pmatrix}$$矩阵乘法有两个必须记住的脾气:
- 不满足交换律:通常 ,所以乘的时候左右顺序千万不能写反!
- 满足结合律:。正是因为可以随便加括号把连乘拆成 ,我们才能像算整数 的快速幂一样,把 按指数 的二进制拆成 次乘法搞定!
此外,矩阵世界里的“数字 1”叫做单位矩阵 ——主对角线(左上到右下)全是 1,其余格子全是 0。任何矩阵乘以 都等于它自己(),这就是快速幂里答案矩阵 res 的初始值。
2. 怎样把递推公式“装进”矩阵里?(固定三步法)
怎样把 变成矩阵乘一次?只要按下面固定三步走:
- 选状态向量(把算下一项需要的“原材料”竖着装进一列): 算 需要用到 和 ,于是定义第 步的状态列向量 $\mathbf{v}_n = \begin{pmatrix} F_{n+1} \\ F_n \end{pmatrix}$。
- 用旧向量表示新向量(每一行都写成旧元素的线性组合):
- 新第 1 行:
- 新第 2 行:
- 把系数抄进矩阵里:$$\begin{pmatrix} F_{n+1} \\ F_n \end{pmatrix} = \underbrace{\begin{pmatrix} 1 & 1 \\ 1 & 0 \end{pmatrix}}_{M} \begin{pmatrix} F_n \\ F_{n-1} \end{pmatrix}$$
大功告成!每左乘一次 ,状态就往前推 步:
- 从初值 $\mathbf{v}_0 = \begin{pmatrix} F_1 \\ F_0 \end{pmatrix} = \begin{pmatrix} 1 \\ 0 \end{pmatrix}$ 出发,左乘 次 ,就得到 $\begin{pmatrix} F_n \\ F_{n-1} \end{pmatrix} = M^{n-1} \begin{pmatrix} 1 \\ 0 \end{pmatrix}$!
- 又因为右边乘的是 ,所以算出 之后,它左上角那个数
(M^(n-1))[0][0]直接就是 !
如果递推式里多了一个常数项(比如 )或者要求前 项和 怎么办?只要在竖列向量里多加一行“常数值 1”或“前缀和 S_n”,照样能把系数抄进矩阵里!
想看更多构造例子点这里:带常数项的三阶递推 & 斐波那契前缀和矩阵
-
带常数项的三阶递推 : 在状态向量末尾塞一个恒等于
$$\begin{pmatrix} a_n \\ a_{n-1} \\ a_{n-2} \\ 1 \end{pmatrix} = \begin{pmatrix} 2 & 1 & 1 & 3 \\ 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \end{pmatrix} \begin{pmatrix} a_{n-1} \\ a_{n-2} \\ a_{n-3} \\ 1 \end{pmatrix}$$1的辅助项:(如果是 ,就把 和 一起放进状态向量,利用 线性转移!)
-
求斐波那契前 项和 : 注意到 ,把 也塞进状态向量:
$$\begin{pmatrix} S_n \\ F_{n+1} \\ F_n \end{pmatrix} = \begin{pmatrix} 1 & 1 & 0 \\ 0 & 1 & 1 \\ 0 & 1 & 0 \end{pmatrix} \begin{pmatrix} S_{n-1} \\ F_n \\ F_{n-1} \end{pmatrix}$$一次 矩阵快速幂就能同时求出 和 !
3. 图论路径计数 & 广义矩阵乘法(min-plus)
矩阵乘法不只是算数列递推,在图论里也有两招绝活:
- 恰好走 步的路径方案数:设 表示从点 走 步直接到点 的边数。想一想 是什么?不就是“先从 一步走到中转点 ,再从 一步走到 ”的总方案数吗!因此 就等于从 到 恰好走 步的路径总数!
- 恰好走 步的最短路(广义矩阵乘法 / min-plus):如果每条边有边权 (没边记作 ),把矩阵乘法公式里的**“求和 ”换成“取最小 ”,把“相乘 ”换成“普通加法 ”**:$$(A \otimes B)_{i, j} = \min_{0 \le r < n} \bigl(A_{i, r} + B_{r, j}\bigr)$$这个新运算依然满足结合律!于是 就等于从 到 恰好走 步的最短路径长度。注意这时的“单位矩阵”对角线是
0(走 步到自己距离为0),其余位置是+INF(走 步到不了别的点)。
手把手带你走一遍例子
下面这张图对比了普通循环和矩阵快速幂的思路差距——把一步步递推换成 的二进制倍增:
现在我们手算一次 ,用它算出斐波那契数列的第 项 (与第 项 )。
因为 的二进制是 101(即 ),所以 :
- 初始状态:
res = I = [[1, 0], [0, 1]],底数base = M = [[1, 1], [1, 0]],指数exp = 5。 - 第 1 轮(
exp = 5,末位是1):需要把当前base(即 )乘进res,res变成[[1, 1], [1, 0]]。随后base自己平方变成 ,指数右移变成exp = 2。 - 第 2 轮(
exp = 2,末位是0):末位为0,不乘进res!res保持不变;base继续自己平方变成 ,指数右移变成exp = 1。 - 第 3 轮(
exp = 1,末位是1):把当前的base(即 )乘进res,得到:$$\text{res} = M^1 \times M^4 = \begin{pmatrix} 1 & 1 \\ 1 & 0 \end{pmatrix} \begin{pmatrix} 5 & 3 \\ 3 & 2 \end{pmatrix} = \begin{pmatrix} 8 & 5 \\ 5 & 3 \end{pmatrix}$$指数右移变成0,循环结束!
把每一步记成状态表:
| 轮次 | 当前指数 exp |
末位 exp & 1 |
本轮操作 | 轮末结果 res |
轮末底数 base |
|---|---|---|---|---|---|
| 初始 | 准备 exp = 5 |
无 | 令 res = I, base = M |
[[1, 0], [0, 1]] () |
[[1, 1], [1, 0]] () |
| 第 1 轮 | 5 (101) |
1 |
res *= base; base *= base |
[[1, 1], [1, 0]] () |
[[2, 1], [1, 1]] () |
| 第 2 轮 | 2 (10) |
0 |
跳过 res; base *= base |
[[1, 1], [1, 0]] (不变) |
[[5, 3], [3, 2]] () |
| 第 3 轮 | 1 (1) |
1 |
res *= base; base *= base |
[[8, 5], [5, 3]] () |
[[34, 21], [21, 13]] () |
看 res 的第一列:[8, 5]!对照手算数列 F_0=0, F_1=1, F_2=1, F_3=2, F_4=3, F_5=5, F_6=8,res.a[0][0] 正好就是 ,res.a[1][0] 正好就是 !
代码拆解:每一段都在干什么
在读完整模板之前,先了解这 5 个关键细节,代码一眼就能看懂:
- 为什么三重循环写
i -> r -> j而不是i -> j -> r? C++ 的二维数组在内存里是一行一行连续排的。写i -> j -> r时,内层读rhs.a[r][j]是在跨行跳跃,缓存命中率很低;改成i -> r -> j之后,内层连续扫描同一行,速度能快很多!而且可以在中层加一句if (a[i][r] == 0) continue;——转移矩阵里通常有很多0,这样直接跳过一整行,常数起飞! - 乘法累加为什么要用到
__int128? 假设模数是 ,那么a[i][r] * rhs.a[r][j]最高能达到 。如果矩阵大小是 ,连续把 个 加在一起再取模,早就把long long(上限约 )撑爆了!用__int128强转乘积再累加取模,或者每加一次就% mod,就能彻底防溢出。 - 为什么单位矩阵对角线写
a[i][i] = 1 % mod? 平时 很大时1 % mod就是1;万一测试数据出现mod == 1(所有答案都要输出0),如果写a[i][i] = 1,当指数exp == 0直接返回单位矩阵时就会错输出1而不是0。写1 % mod就能顺便兜住这个边界。 - 求 到底是算 还是 ?
因为我们的初始向量是 $\begin{pmatrix} F_1 \\ F_0 \end{pmatrix} = \begin{pmatrix} 1 \\ 0 \end{pmatrix}$(下标已经到了
1),乘一次 得到 ,所以乘n - 1次 后右上和左上变成 ,返回P.a[0][0]就是 !单独把n == 0和n == 1特判掉就行。 MinPlusMatrix里的INF为什么设4e18而不是LLONG_MAX? 因为广义矩阵乘法里要算a[i][r] + rhs.a[r][j]!如果把INF设成LLONG_MAX,两个无穷大相加(或无穷大加正权边)会直接溢出变成负数!设成4e18并且在相加前先if (a[i][r] >= INF) continue;,既够大又绝对不会溢出。
C++ 代码模板(带逐行中文注释)
#include <algorithm>
#include <cassert>
#include <vector>
using int64 = long long;
/**
* 1. 通用模意义方阵结构体(n x n)
* 支持:构建零矩阵 / 单位矩阵、缓存友好乘法(防溢出)、快速幂
*/
struct Matrix {
int n; // 方阵边长
int64 mod; // 取模模数
std::vector<std::vector<int64>> a;
// ident = true 时构造单位矩阵 I,false 时构造全 0 矩阵
Matrix(int n_, int64 mod_, bool ident = false)
: n(n_), mod(mod_), a(n_, std::vector<int64>(n_, 0)) {
assert(n_ >= 1 && mod_ >= 1);
if (ident) {
for (int i = 0; i < n; ++i) {
a[i][i] = 1 % mod; // 对角线置 1(写 1 % mod 兼容 mod == 1)
}
}
}
// 重载 * 实现矩阵乘法:O(n^3)
Matrix operator*(const Matrix& rhs) const {
assert(n == rhs.n && mod == rhs.mod);
Matrix res(n, mod, false);
for (int i = 0; i < n; ++i) {
for (int r = 0; r < n; ++r) { // 采用 i -> r -> j 顺序提高缓存命中率
if (a[i][r] == 0) continue; // 跳过 0 元素,对稀疏转移矩阵提速明显
int64 air = a[i][r];
for (int j = 0; j < n; ++j) {
// 用 __int128 接住乘积,防止 a[i][r] * rhs.a[r][j] 累加后溢出 long long
res.a[i][j] = static_cast<int64>(
(res.a[i][j] + static_cast<__int128>(air) * rhs.a[r][j]) % mod
);
}
}
}
return res;
}
};
/**
* 矩阵快速幂:计算 base^exp (mod base.mod)
* 时间复杂度:O(n^3 log exp)
*/
Matrix mat_pow(Matrix base, int64 exp) {
assert(exp >= 0);
Matrix res(base.n, base.mod, true); // 答案初始化为单位矩阵 I(相当于数字 1)
while (exp > 0) {
if (exp & 1) { // exp 当前二进制最低位为 1,乘入答案
res = res * base;
}
base = base * base; // 底数矩阵平方倍增
exp >>= 1;
}
return res;
}
/**
* 2. 斐波那契第 n 项模 mod(O(log n))
* 约定:F_0 = 0, F_1 = 1, F_2 = 1, F_3 = 2, ...
*/
int64 fibonacci_mod(int64 n, int64 mod) {
assert(n >= 0 && mod >= 1);
if (n == 0) return 0;
if (n == 1) return 1 % mod;
Matrix M(2, mod);
M.a = {{1 % mod, 1 % mod},
{1 % mod, 0}};
Matrix P = mat_pow(M, n - 1); // [F_n, F_{n-1}]^T = M^(n-1) * [1, 0]^T
return P.a[0][0]; // 第一行第一列正好就是 F_n
}
/**
* 3. min-plus 广义矩阵乘法(用于求恰好走 k 步的最短路)
* 运算规则:C[i][j] = min_r (A[i][r] + B[r][j])
*/
struct MinPlusMatrix {
static constexpr int64 INF = 4'000'000'000'000'000'000LL; // 4e18,安全无穷大
int n;
std::vector<std::vector<int64>> a;
MinPlusMatrix(int n_, bool ident = false)
: n(n_), a(n_, std::vector<int64>(n_, INF)) {
if (ident) {
// 广义单位矩阵:走 0 步到自己距离是 0,到其他点不可达 (+INF)
for (int i = 0; i < n; ++i) a[i][i] = 0;
}
}
MinPlusMatrix operator*(const MinPlusMatrix& rhs) const {
assert(n == rhs.n);
MinPlusMatrix res(n, false);
for (int i = 0; i < n; ++i) {
for (int r = 0; r < n; ++r) {
if (a[i][r] >= INF) continue; // 不可达直接跳过,防止 INF 相加溢出
for (int j = 0; j < n; ++j) {
if (rhs.a[r][j] >= INF) continue;
res.a[i][j] = std::min(res.a[i][j], a[i][r] + rhs.a[r][j]);
}
}
}
return res;
}
};
MinPlusMatrix min_plus_pow(MinPlusMatrix base, int64 exp) {
assert(exp >= 0);
MinPlusMatrix res(base.n, true); // 初始化为广义单位矩阵(对角线 0,其余 INF)
while (exp > 0) {
if (exp & 1) res = res * base;
base = base * base;
exp >>= 1;
}
return res;
}
点击展开:完整可运行主程序示例(含斐波那契与恰好 k 步最短路验证)
#include <algorithm>
#include <cassert>
#include <iostream>
#include <vector>
using namespace std;
using int64 = long long;
struct Matrix {
int n;
int64 mod;
vector<vector<int64>> a;
Matrix(int n_, int64 mod_, bool ident = false)
: n(n_), mod(mod_), a(n_, vector<int64>(n_, 0)) {
assert(n_ >= 1 && mod_ >= 1);
if (ident) {
for (int i = 0; i < n; ++i) a[i][i] = 1 % mod;
}
}
Matrix operator*(const Matrix& rhs) const {
assert(n == rhs.n && mod == rhs.mod);
Matrix res(n, mod, false);
for (int i = 0; i < n; ++i) {
for (int r = 0; r < n; ++r) {
if (a[i][r] == 0) continue;
int64 air = a[i][r];
for (int j = 0; j < n; ++j) {
res.a[i][j] = static_cast<int64>(
(res.a[i][j] + static_cast<__int128>(air) * rhs.a[r][j]) % mod
);
}
}
}
return res;
}
};
Matrix mat_pow(Matrix base, int64 exp) {
assert(exp >= 0);
Matrix res(base.n, base.mod, true);
while (exp > 0) {
if (exp & 1) res = res * base;
base = base * base;
exp >>= 1;
}
return res;
}
int64 fibonacci_mod(int64 n, int64 mod) {
assert(n >= 0 && mod >= 1);
if (n == 0) return 0;
if (n == 1) return 1 % mod;
Matrix M(2, mod);
M.a = {{1 % mod, 1 % mod}, {1 % mod, 0}};
return mat_pow(M, n - 1).a[0][0];
}
struct MinPlusMatrix {
static constexpr int64 INF = 4'000'000'000'000'000'000LL;
int n;
vector<vector<int64>> a;
MinPlusMatrix(int n_, bool ident = false)
: n(n_), a(n_, vector<int64>(n_, INF)) {
if (ident) {
for (int i = 0; i < n; ++i) a[i][i] = 0;
}
}
MinPlusMatrix operator*(const MinPlusMatrix& rhs) const {
MinPlusMatrix res(n, false);
for (int i = 0; i < n; ++i) {
for (int r = 0; r < n; ++r) {
if (a[i][r] >= INF) continue;
for (int j = 0; j < n; ++j) {
if (rhs.a[r][j] >= INF) continue;
res.a[i][j] = min(res.a[i][j], a[i][r] + rhs.a[r][j]);
}
}
}
return res;
}
};
MinPlusMatrix min_plus_pow(MinPlusMatrix base, int64 exp) {
MinPlusMatrix res(base.n, true);
while (exp > 0) {
if (exp & 1) res = res * base;
base = base * base;
exp >>= 1;
}
return res;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
const int64 MOD = 1'000'000'007LL;
assert(fibonacci_mod(0, MOD) == 0);
assert(fibonacci_mod(1, MOD) == 1);
assert(fibonacci_mod(6, MOD) == 8);
assert(fibonacci_mod(10, MOD) == 55);
assert(fibonacci_mod(1'000'000'000'000LL, MOD) == 730695249LL);
cout << "F_10 = " << fibonacci_mod(10, MOD) << '\n';
cout << "F_1000000000000 mod 1e9+7 = "
<< fibonacci_mod(1'000'000'000'000LL, MOD) << '\n';
// min-plus 示例:3 个点的有向图 0->1 (权2), 1->2 (权3), 0->2 (权10),走恰好 2 步从 0 到 2 最短距离为 5
MinPlusMatrix G(3, false);
G.a[0][1] = 2;
G.a[1][2] = 3;
G.a[0][2] = 10;
auto G2 = min_plus_pow(G, 2);
assert(G2.a[0][2] == 5);
cout << "恰好走 2 步从 0 到 2 的最短距离 = " << G2.a[0][2] << '\n';
return 0;
}
常见变形与怎么认出这类题
- 大下标计数 DP(棋盘铺砖、字符串计数、有限状态自动机)
- 题面关键词:给你一个很大的长度 ,每一步只和上一层几个状态有关,且每一层的转移规则完全相同、状态数 很小(如 )。
- 怎么转化:把原本 的 DP 转移写成 矩阵,用矩阵快速幂降到 !
- 矩阵幂次求和:
- 题面关键词:不仅求第 项,而是求矩阵前 次幂之和,或高阶递推前 项之和。
- 怎么转化:如果只想省事,可以直接把 塞进状态向量;如果给你一个现成矩阵 求 ,可以用二分折半递归: 为偶数时 , 为奇数时 ,矩阵大小不用翻倍,常数非常小。
- 多组询问查同一个固定递推式( 单次查询)
- 题面关键词:有 个询问,每次只改变 ,递推矩阵 不变。
- 怎么转化:提前算好 ()存起来。每次问 时,拿初始列向量 依次去乘二进制位为 的那些 !“矩阵乘向量”一次只需 而不是 ,总速度直接快 倍!
新手最容易踩的坑
- 把左右乘顺序写反:矩阵乘法不满足交换律!采用列向量 时,答案是 (矩阵在左,向量在右);如果采用行向量,矩阵要转置且向量放左边。固定死一种习惯,别混着用。
- 幂次差 (Off-by-one):求 到底是算
mat_pow(M, n)还是mat_pow(M, n - 1)?写完代码第一时间拿 代进去跑一遍,和手算值对比一下最保险。 - 累加忘记防溢出:模数 时一次乘积最大 ,在循环里连续累加好几次不取模就会爆
long long,请务必使用__int128或每次累加立刻% mod。 - 初始矩阵里的负数没处理:如果题目递推式里出现减法(例如 ),往矩阵里填
-1时必须规范化为(-1 % mod + mod) % mod! - 把普通单位矩阵套进
min-plus矩阵里:min-plus的单位矩阵对角线是0(不是1!),其余位置是INF(不是0!),而且INF不能设LLONG_MAX否则相加溢出。