跳到正文

个人记录

【题解】Firework

qW__Wp约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月16日
更新
2025年12月16日
篇幅
约 4 分钟

版本

  1. v2当前
  2. v1

矩阵加速学习笔记

题意

给定 n,m,kn,m,k,试求有多少长度为 nn 的环状 01\texttt{01} 串满足任意长度为 kk 的子串中 11 的数量不超过 kk。

2≤n≤1015,2≤m≤min⁡(n,5),1≤k<m2 \le n \le 10^{15}, 2 \le m \le \min(n, 5), 1 \le k < m。

mm 较小,考虑状压。设 fi,Sf_{i,S} 表示考虑前 ii 位,最后 mm 位的状态为 SS 的方案数。

若可以从 fi−1,S′f_{i-1,S'} 转移而来,易得 S′S' 的后 m−1m-1 位必须与 SS 的前 m−1m-1 位相同,于是有转移

fi,S←fi−1,S>>1+fi−1,(S>>1)+2m−1f_{i,S} \gets f_{i-1, S >> 1} + f_{i-1, (S >> 1) + 2^{m-1}}

对于环上问题,我们要求第 n+1n + 1 位的状态与第 11 位相同。即枚举初始状态 TT,答案取 fn+1,Tf_{n+1,T}。直接实现的时间复杂度为 O(2mn)O(2^m n)。


注意到状态 ii 到状态 jj 是否转移是固定的,考虑构造一个 2m×2m2 ^ m \times 2 ^ m 的转移矩阵 BB,使:

[fi,S1fi,S2…]=[fi−1,S1fi−1,S2…]×B\begin{bmatrix} f_{i,S_1} & f_{i,S_2} & \dots & \end{bmatrix} = \begin{bmatrix} f_{i-1,S_1} & f_{i-1,S_2} & \dots & \end{bmatrix} \times B

转移矩阵的构造方法:当状态 jj 可以转移到状态 ii 时,Bi,j=1B_{i,j} = 1,否则为 00。如果难以理解,可以模拟矩阵乘法的过程。

通过矩阵快速幂计算 BnB^n,由于最终状态必须与初始状态相同,答案即为 ∑iBi,in\sum_{i} B^n_{i,i}。

时间复杂度 O(23mlog⁡n)O(2^{3m} \log n)。

Code
C++
#include <bits/stdc++.h>
#define endl '\n'

using namespace std;

typedef long long ll;

const int N = 1e5 + 5, Mod = 1e9 + 7;

int f[N][40];
int h[N][40];
ll n;
int m, k;

struct Matrix {
	int a[32][32];
	Matrix () { memset(a, 0, sizeof a); }
	Matrix operator*(const Matrix& other) const {
		Matrix res;
		for (int i = 0; i < (1 << m); i ++) {
			for (int j = 0; j < (1 << m); j ++) {
				for (int k = 0; k < (1 << m); k ++) {
					res.a[i][j] = (0ll + res.a[i][j] + 1ll * a[i][k] * other.a[k][j] % Mod) % Mod;
				}
			}
		}
		return res;
	}
} bs;

signed main() {
	freopen("firework.in", "r", stdin);
	freopen("firework.out", "w", stdout);
	ios::sync_with_stdio(0), cin.tie(0);
	cin >> n >> m >> k;
	for (int i = 0; i < (1 << m); i ++) {
		if (__builtin_popcount(i) > k) continue;
		if (__builtin_popcount(i >> 1) <= k) bs.a[i >> 1][i] = 1;
		int l = (i >> 1) + (1 << (m - 1));
		if (__builtin_popcount(l) <= k) bs.a[l][i] = 1;
	}
	Matrix res;
	for (int i = 0; i < (1 << m); i ++) res.a[i][i] = 1;
	ll x = n;
	while (x) {
		if (x & 1) res = res * bs;
		bs = bs * bs, x >>= 1;
	}
	int ans = 0;
	for (int i = 0; i < (1 << m); i ++) {
		ans = (ans + res.a[i][i]) % Mod;
	}
	cout << ans;
	return 0;
}
原文