矩阵快速幂的模板:
struct matrix{
LL f[10][10];
int r,c;
matrix(int _r=0,int _c=0){
r=_r,c=_c;
memset(f,0,sizeof(f));
}
void output(){
for(int i=1;i<=r;i++){
for(int j=1;j<=c;j++){
cout<<f[i][j]<<" ";
}
cout<<endl;
}
}
};
matrix mul(matrix &A,matrix &B){
matrix C;
C.r=A.r,C.c=B.c;
for(int i=1;i<=A.r;i++){
for(int j=1;j<=B.c;j++){
for(int k=1;k<=A.c;k++){
C.f[i][j]=(C.f[i][j]+A.f[i][k]*B.f[k][j]%MOD)%MOD;
}
}
}
return C;
}
matrix mqpow(matrix A,LL x){
matrix res;
res.r=A.r,res.c=A.c;
for(int i=1;i<=res.r;i++){
for(int j=1;j<=res.c;j++){
if(i!=j)res.f[i][j]=0;
else res.f[i][j]=1;
}
}
while(x){
if(x%2==0){
A=mul(A,A);
x=x/2;
}
else{
res=mul(res,A);
x=x-1;
}
}
return res;
}
用到矩阵快速幂的模板题
题目:hdu 6395 Sequence
AC代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MAX_N=1e7+20;
const int MAXN=20010;
const int MAXM=50010;
const LL INF=0x3f3f3f3f3f3f;
const LL MOD=1e9+7;
int T;
LL A,B,C,D,P,n;
struct matrix{
LL f[10][10];
int r,c;
matrix(int _r=0,int _c=0){
r=_r,c=_c;
memset(f,0,sizeof(f));
}
void output(){
for(int i=1;i<=r;i++){
for(int j=1;j<=c;j++){
cout<<f[i][j]<<" ";
}
cout<<endl;
}
}
};
matrix mul(matrix &A,matrix &B){
matrix C;
C.r=A.r,C.c=B.c;
for(int i=1;i<=A.r;i++){
for(int j=1;j<=B.c;j++){
for(int k=1;k<=A.c;k++){
C.f[i][j]=(C.f[i][j]+A.f[i][k]*B.f[k][j]%MOD)%MOD;
}
}
}
return C;
}
matrix mqpow(matrix A,LL x){
matrix res;
res.r=A.r,res.c=A.c;
for(int i=1;i<=res.r;i++){
for(int j=1;j<=res.c;j++){
if(i!=j)res.f[i][j]=0;
else res.f[i][j]=1;
}
}
while(x){
if(x%2==0){
A=mul(A,A);
x=x/2;
}
else{
res=mul(res,A);
x=x-1;
}
}
return res;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
//freopen("1.in","r",stdin);
cin>>T;
while(T--){
cin>>A>>B>>C>>D>>P>>n;
if(n==1){
cout<<A<<endl;
continue;
}
if(n==2){
cout<<B<<endl;
continue;
}
LL F1=A,F2=B,k=P;
matrix M(3,3);
M.f[1][1]=0,M.f[1][2]=1,M.f[1][3]=0;
M.f[2][1]=C,M.f[2][2]=D,M.f[2][3]=1;
M.f[3][1]=0,M.f[3][2]=0,M.f[3][3]=1;
LL cur=2;
for(LL i=P;i>=0;i=P/(cur+1)){
LL l,r;
l=P/(i+1);
if(i!=0)r=P/i;
else r=INF;
//cout<<l<<" "<<r<<endl;
if(l>=r)continue;
if(cur>=r)continue;
matrix tmp(3,1);
tmp.f[1][1]=F1,tmp.f[2][1]=F2,tmp.f[3][1]=i;
// tmp.output();
if(n<=r){
LL x=n-cur;
matrix _=mqpow(M,x);
tmp=mul(_,tmp);
F1=tmp.f[1][1],F2=tmp.f[2][1];
cur=n;
break;
}
else{
LL x=r-cur;
matrix _=mqpow(M,x);
tmp=mul(_,tmp);
F1=tmp.f[1][1],F2=tmp.f[2][1];
cur=n;
cur=r;
}
//cout<<F2<<endl;
}
cout<<F2<<endl;
}
}