Matrix Multiplication (& Quick Power)
Description
一个长度为L的队列,里面排列着男人和女人,分别用f和m表示。
计算出长度为L的队列中,不含子串fff和fmf的队列个数,并对一个数M取模。
Type
Matrix Multiplication
Quick Power
Analysis
这种题目很像递推题,没错它就是递推题。
考虑当前长度为L的队列,和长度小于L的队列的关系,看能不能找到递推关系。
我们可以试图在长度小于L且符合条件的队列后面加上几个元素,使之长度为L,又不含fff和fmf。
我们发现,在长度为L – 1、L – 3、L – 4的队列后面加上m、ffm、ffmm,都可以得到符合条件的队列。
所以,长度为L的符合条件的队列的数量,就等于有几条长度为L – 1、L – 3、L – 4的队列之和。
可以设长度为L的符合条件的队列数量为F(L),则得到递推公式:
- F(L) = F(L – 1) + F(L – 3) + F(L - 4)
既然有了递推公式,我们就可以构造矩阵,用矩阵乘法和快速幂来求解了。
需要构造的矩阵如下:
不过,在知道这种方法之前,我不是这样做的,囧。
我先写了一个代码暴力地求解答案,然后从答案中间发现了另外一个规律。
设x和y为当前项的前两项,从第三项开始,每四项与他们的前两项的关系是:
- x + y
- x + y - 1
- x + y
- x + y + 1
然后进行矩阵乘法和快速幂求解。
1. 暴力求解找规律
// HDOJ 2604
// Queuing
// by A Code Rabbit
#include <iostream>
#include <string>
using namespace std;
int ans;
int n;
void Search(string str);
int main() {
while (cin >> n) {
ans = 0;
Search("");
cout << ans << endl;
}
}
void Search(string str) {
if (str.length() >= n) {
if (str.find("fmf") == string::npos &&
str.find("fff") == string::npos)
{
ans++;
}
return;
}
Search(str + "f");
Search(str + "m");
}
2. 递推 + 矩阵乘法 + 快速幂
// HDOJ 2604
// Queuing
// by A Code Rabbit
#include <cstdio>
#include <cstring>
const int MAXO = 5;
int MOD;
template <typename T>
struct Matrix {
T e[MAXO][MAXO];
int o;
Matrix(int x) { memset(e, 0, sizeof(e)); o = x; }
Matrix operator*(const Matrix& one) {
Matrix res(o);
for (int i = 0; i < o; i++) {
for (int j = 0; j < o; j++) {
for (int k = 0; k < o; k++)
res.e[i][j] += e[i][k] * one.e[k][j];
res.e[i][j] %= MOD;
}
}
return res;
}
Matrix operator*=(const Matrix& one) { return *this = *this * one; }
};
template <typename T>
T QuickPower(T radix, int exp) {
T res = radix;
exp--;
while (exp) {
if (exp & 1) res *= radix;
exp >>= 1;
radix *= radix;
}
return res;
}
int l, m;
const int INIT[] = {
5, 3, 2, 1, 0,
3, 2, 1, 1, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
1, 1, 1, 0, 1,
};
Matrix<int> mat_one(5);
const int ans[] = { 9, 6, 4, 2, 1, };
int main() {
while (scanf("%d%d", &l, &m) != EOF) {
// INIT.
memcpy(mat_one.e, INIT, sizeof(INIT));
// Quick Sort.
int num = (l - 1) / 4;
MOD = m;
Matrix<int> mat_ans = QuickPower(mat_one, num);
// Compute and output.
int ans_sum = 0;
for (int i = 0; i < 5; ++i)
ans_sum += ans[i] * mat_ans.e[i][4 - ((l - 1) % 4 + 1)];
printf("%d\n", ans_sum % m);
}
return 0;
}