hdu_5950_Recursive sequence(矩阵快速幂)

时间:2021-08-12 20:35:56

题目链接:hdu_5950_Recursive sequence

题意:递推求解:F(n) = 2*F(n-2) + F(n-1) + n和F(1) = a,F(2) = b;

题解:

一看数据范围,肯定矩阵加速递推,不过公式不是线性的,需要把公式转换为线性的公式

hdu_5950_Recursive sequence(矩阵快速幂)

 #include<bits/stdc++.h>
#define F(i,a,b) for(int i=a;i<=b;i++)
using namespace std;
typedef long long ll; const int mat_N=;
ll mo=; struct mat{
ll c[mat_N][mat_N];
void init(){memset(c,,sizeof(c));}
mat operator*(mat b){
mat M;int N=mat_N-;M.init();
F(i,,N)F(j,,N)F(k,,N)M.c[i][j]=(M.c[i][j]+c[i][k]*b.c[k][j])%mo;
return M;
}
mat operator^(ll k){
mat ans,M=(*this);int N=mat_N-;ans.init();
F(i,,N)ans.c[i][i]=;
while(k){if(k&)ans=ans*M;k>>=,M=M*M;}
return ans;
}
}A,B,C; int t,n,a,b; int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%d%d%d",&n,&a,&b);
A=(mat){,,,,,,,
,,,,,,,
,,,,,,,
,,,,,,,
,,,,,,,
,,,,,,,
,,,,,,};
C=A^(n-);
ll ans=;
ans=(C.c[][]*a+C.c[][]*b+C.c[][]*+C.c[][]*+C.c[][]*+C.c[][]*+C.c[][])%mo;
printf("%lld\n",ans);
}
return ;
}