洛谷题单指南-基础线性代数-P4910 帕秋莉的手环
原题链接:https://www.luogu.com.cn/problem/P4910
题意解读:长度为n的01环形串,相邻两个必有一个是1,求组成这样的01串的方案数。
解题思路:
设f[i][0]表示长度为i的01串,相邻两个必有一个是1,且第i个是0的方案数
设f[i][1]表示长度为i的01串,相邻两个必有一个是1,且第i个是1的方案数。
则有:
f[i][0] = f[i-1][1]
f[i][1] = f[i-1][0] + f[i-1][1]
如果第一个是0,那么答案是f[n][1],如果第一个是1,那么答案是f[n][0] + f[n][1]
由于n的范围很大,显然要使用矩阵快速幂来优化。

100分代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL mod = 1000000007;
LL t, n;
struct Matrix
{
LL a[3][3];
Matrix()
{
memset(a, 0, sizeof(a));
}
Matrix operator * (const Matrix &to) 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] * to.a[k][j]) % mod;
return res;
}
};
Matrix ksm(Matrix &a, LL b)
{
Matrix res;
res.a[1][1] = res.a[2][2] = 1;
while(b)
{
if(b & 1) res = res * a;
a = a * a;
b >>= 1;
}
return res;
}
int main()
{
cin >> t;
while (t--)
{
cin >> n;
Matrix A, B, f, g;
A.a[1][1] = 0, A.a[1][2] = 1, A.a[2][1] = 1, A.a[2][2] = 1;
B.a[1][1] = 0, B.a[1][2] = 1, B.a[2][1] = 1, B.a[2][2] = 1;
//第一个是0
f.a[1][1] = 1, f.a[1][2] = 0;
//第一个是1
g.a[1][1] = 0, g.a[1][2] = 1;
LL ans = 0;
Matrix res = f * ksm(A, n - 1);
ans = (ans + res.a[1][2]) % mod;
res = g * ksm(B, n - 1);
ans = (ans + res.a[1][1] + res.a[1][2]) % mod;
cout << ans << endl;
}
return 0;
}
浙公网安备 33010602011771号