您的位置:首页 > 其它

[HDU1757]A Simple Math Problem(矩阵快速幂)

2016-05-23 14:24 441 查看

题目描述

传送门

题意

f(i)的定义看题面吧,就是那个递推式。

给定n,Mod,求f(n),答案对Mod取模。

题解

简单的矩阵加速dp题目。

令A=[fn−1fn−2⋯fn−10]

B=⎡⎣⎢⎢⎢⎢⎢a1a2⋮a1010⋮001⋮0⋯⋯⋱⋯00⋮1⎤⎦⎥⎥⎥⎥⎥

则A∗Bn−9即为答案

代码

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
#define LL long long
LL n,Mod;
struct hp{LL a[20][20];}unit,A,m,ans;

inline hp cheng(hp a,hp b)
{
hp ans;
memset(ans.a,0,sizeof(ans.a));
for (int i=1;i<=10;++i)
for (int j=1;j<=10;++j)
for (int k=1;k<=10;++k)
ans.a[i][j]=(ans.a[i][j]+a.a[i][k]*b.a[k][j]%Mod)%Mod;
return ans;
}
inline hp matrix_fast_pow(hp a,LL p)
{
hp ans=unit;
for (;p;p>>=1,a=cheng(a,a))
if (p&1)
ans=cheng(ans,a);
return ans;
}
int main()
{
for (int i=1;i<=10;++i) unit.a[i][i]=1;
for (int i=9;i>=0;--i) A.a[1][10-i]=(LL)i;
for (int i=2;i<=10;++i) m.a[i-1][i]=1;
while (~scanf("%I64d%I64d",&n,&Mod))
{
for (int i=1;i<=10;++i) scanf("%I64d",&m.a[i][1]);
ans=matrix_fast_pow(m,n-9);
ans=cheng(A,ans);
printf("%I64d\n",ans.a[1][1]);
}
}


总结

注意矩阵不满足交换律。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: