矩阵快速幂
矩阵优化可以经常利用在递推式中。
首先了解一下矩阵乘法的法则。
\(\begin{bmatrix}a&b\\c&d\end{bmatrix}\) \(\times\) \(\begin{bmatrix}e&f\\g&h\end{bmatrix}\) \(=\) \(\begin{bmatrix} a \times e + b \times g & a \times f + b \times h \\ c \times e + d \times g & c \times f + d \times h \end{bmatrix}\)
这就貌似非常简单了。
看一个例题,斐波那契数列不同于一般的斐波那契数列,\(n\)在\(long\) \(long\)之内,所以\(O(n)\)绝对会超时,这是需要矩阵快速幂,复杂度是\(O(3^3logn)\) \(=\) \(O(27log n)\),忽略常数,那么复杂度就是\(O(logn)\)
我们定义一个矩阵等式,然后去求问号矩阵
\(\begin{bmatrix} f[i+1] & f[i]\end{bmatrix}\) \(\times\) \(\begin{bmatrix}? \end{bmatrix}\) \(=\) \(\begin{bmatrix}f[i+2] & f[i+1] \end{bmatrix}\)
\(f[i+2] = f[i] + f[i+1]\)
构造的\(?\)号矩阵就是
\(\begin{bmatrix} 1 & 1 \\ 1 & 0\end{bmatrix}\)
带回检验
\(\begin{bmatrix}f[i+1] & f[i] \\ 0 & 0\end{bmatrix} \times \begin{bmatrix} 1 & 1 \\ 1 & 0\end{bmatrix} = \begin{bmatrix}f[i+1] \times 1 + f[i] \times 1 & f[i+1] \times 1 + f[i] \times 0 \\ 0 \times 1 + 0 \times 1 & 0 \times 1 + 0 \times 0 \end{bmatrix}\)
上式化简为
\(\begin{bmatrix}f[i+2] & f[i+1] \\ 0 & 0\end{bmatrix} = \begin{bmatrix}f[i+2] & f[i+1]\end{bmatrix}\)
所以成立.
矩阵快速幂模板代码就是
struct Mat {
int a[3][3];
Mat() {memset(a,0,sizeof a);}
inline void build() {
memset(a,0,sizeof a);
for(re int i = 1 ; i <= 2 ; ++ i) a[i][i]=1;
}
};
Mat operator*(Mat &a,Mat &b)
{
Mat c;
for(re int k = 1 ; k <= 2 ; ++ k)
for(re int i = 1 ; i <= 2 ; ++ i)
for(re int j = 1 ; j <= 2 ; ++ j)
c.a[i][j]=(c.a[i][j]+a.a[i][k]*b.a[k][j]%mod)%mod;
return c;
}
Mat quick_Mat(int x)
{
Mat ans;ans.build();
while(x) {
if((x&1)==1) ans = ans * a;
a = a * a;
x >>= 1;
}
return ans;
}
例题代码是
#include <cstdio>
#include <iostream>
#include <cmath>
#include <cstring>
#include <queue>
#include <stack>
#define re register
#define Max 200000012
#define int long long
int n;
const int mod=1000000007;
struct Mat {
int a[3][3];
Mat() {memset(a,0,sizeof a);}
inline void build() {
memset(a,0,sizeof a);
for(re int i = 1 ; i <= 2 ; ++ i) a[i][i]=1;
}
};
Mat operator*(Mat &a,Mat &b)
{
Mat c;
for(re int k = 1 ; k <= 2 ; ++ k)
for(re int i = 1 ; i <= 2 ; ++ i)
for(re int j = 1 ; j <= 2 ; ++ j)
c.a[i][j]=(c.a[i][j]+a.a[i][k]*b.a[k][j]%mod)%mod;
return c;
}
Mat a;
Mat quick_Mat(int x)
{
Mat ans;ans.build();
while(x) {
if((x&1)==1) ans = ans * a;
a = a * a;
x >>= 1;
}
return ans;
}
signed main()
{
scanf("%lld",&n);
a.a[1][1]=1;a.a[1][2]=1;
a.a[2][1]=1;Mat b;
b.a[1][1]=1;b.a[2][1]=1;
if(n>=1 && n<=2) {
printf("1");return 0;
}
Mat ans=quick_Mat(n-2);
ans=ans*b;
printf("%lld",ans.a[1][1]);
return 0;
}