矩阵快速幂
Refined_heart · · 个人记录
先上代码:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#define mod 1000000007
#define ll long long
#define res register
using namespace std;
struct node{
ll s[4][4];
}w;
inline long long read(){
ll s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){
if(ch=='-')
w=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9'){
s=s*10+ch-48;
ch=getchar();
}
return s*w;
}
inline node change(node x,node y){
node c;
memset(c.s,0,sizeof(c.s));
for(res int i=1;i<=3;i++)
for(res int j=1;j<=3;j++)
for(res int k=1;k<=3;k++){
c.s[i][j]+=(x.s[i][k]*y.s[k][j])%mod;
c.s[i][j]%=mod;
}
return c;
}
inline node fast(node x,ll y){
node ans=x;
if(y<=1)
return x;
y--;
while(y>0){
if(y&1)
ans=change(ans,x);
x=change(x,x);
y/=2;
}
return ans;
}
int main(){
int t;
t=read();
memset(w.s,0,sizeof(w));
w.s[1][1]=w.s[3][1]=w.s[1][2]=w.s[2][3]=1;
while(t--){
int k;
k=read();
node q;
memset(q.s,0,sizeof(q.s));
q=fast(w,k-1);
cout<<q.s[1][1]<<endl;
}
return 0;
}
跑了38ms,不是很快……
改天补讲解
矩阵快速幂的主要作用在于优化。当你要求一个数列的10的n次方项时,由于1000ms的时限,绝对会线性爆炸。于是我们考虑加速。
模板:P1939数列加速
首先,对于矩阵乘法,不相当于普通的横纵坐标一一对应的相乘,所以我们要写独特的change函数来模拟矩阵乘法。然后根据快速幂的套路,一次次算就好了……
可惜,难点不在这……
问题在于,对于每一题,都有其独特的单位矩阵,需要自己推。例如上面我的单位矩阵,ans是1,1。题目难度的不同,考验的点也是不同的。
讲解考完期末补吧……
2019.1.17, 期末考试
复杂度为
考试完了……
两天考试挂了,luogu你tm告诉我是中平……
凉啦……凉啦……