struct mat{
ll s[N][N];
mat(){
memset(s,0,sizeof s);
}
mat operator *(const mat c){
mat ans ;
memset(ans.s,0, sizeof ans.s);
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
for(int t=0;t<N;t++)
ans.s[i][j] =(ans.s[i][j]+ s[i][t]*c.s[t][j])%mod;
return ans;
}
mat operator % (int mod){
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
s[i][j] %= mod;
return *this;
}
mat operator + (const mat c){
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
s[i][j] += c.s[i][j];
return *this;
}
mat operator - (const mat c){
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
s[i][j] -= c.s[i][j];
return *this;
}
void print(){
for(int i=0;i<N;i++){
for(int j=0;j<N;j++)
cout<<s[i][j]<<' ';
cout<<endl;
}
}
mat operator ^ (ll k){
mat res,a;
memcpy(a.s,s,sizeof a.s);
for(int i=0;i<N;i++) res.s[i][i]=1;
while(k){
if(k&1) res = res*a;
a =a*a;
k >>= 1;
}
return res;
}
};
上面是我的基本矩阵快速幂模板,其实矩阵快速幂难的不是你怎么写,难的是你矩阵怎么构造。
矩阵的构造,就是找递推关系。
要把需要用到的递推关系包含操作矩阵上去。找到合适的初始向量和合适的操作矩阵,你基本就可以完成题目了。
然后还要注意一下相关的优化,就是矩阵模板的一些多余的操作重载应该注释掉,实现一个较简单的结构体;优化取模,优化操作边界
附上hust自己给自己挂的一套题,自己其实也没做完,才做了5道。