题目
Lele now is thinking about a simple function f(x).
If x < 10 f(x) = x.
If x >= 10 f(x) = a0 * f(x-1) + a1 * f(x-2) + a2 * f(x-3) + …… + a9 * f(x-10);
And ai(0<=i<=9) can only be 0 or 1 .
Now, I will give a0 ~ a9 and two positive integers k and m ,and could you help Lele to caculate f(k)%m.
Input
The problem contains mutiple test cases.Please process to the end of file.
In each case, there will be two lines.
In the first line , there are two positive integers k and m. ( k<2*10^9 , m < 10^5 )
In the second line , there are ten integers represent a0 ~ a9.
Output
For each case, output f(k) % m in one line.
Sample Input
10 9999
1 1 1 1 1 1 1 1 1 1
20 500
1 0 1 0 1 0 1 0 1 0
Sample Output
45
104
题目大意
多个测试样例
输入n和mod
再输入n个ai
要求输出Fn
算法:矩阵快速幂
分析
一开始想递归,但是 k<2*10^9,肯定超时
然后不会做,百度告诉我矩阵快速幂
这个是矩阵快速幂的介绍https://www.cnblogs.com/cmmdc/p/6936196.html
然后又看到一篇文章https://blog.csdn.net/qq_41287489/article/details/80331398
这一篇里边点到了这道题的方法,也就是下图
那么其实可以推出这道题的矩阵幂
然后你就可以按照快速幂的模板来写了
要知道你求的是Fn,所以最后只要将res第一行与987654321相乘就ok
代码
#include<iostream>
#include<cstring>
using namespace std;
int m,mod;
const int N=10; //矩阵维数
int a[N][N],res[N][N],temp[N][N]; //a是需要次方的矩阵 ,res是a次方后的结果矩阵,tenp当做临时矩阵
void mul(int a[][N],int b[][N]) //矩阵乘法函数
{
memset(temp,0,sizeof(temp));
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
for(int k=0;k<N;k++)
temp[i][j]=(temp[i][j]+a[i][k]*b[k][j]%mod)%mod;
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
a[i][j]=temp[i][j];
}
void fun(int a[][N],int n) //矩阵快速幂函数
{
memset(res,0,sizeof(res));
for(int i=0;i<N;i++)
res[i][i]=1; //单位矩阵
while(n)
{
if(n&1) mul(res,a);
mul(a,a);
n>>=1;
}
}
int main()
{
while(cin>>m>>mod)
{
memset(a,0,sizeof(a));
for(int i=0;i<N;i++)
cin>>a[0][i]; //要求幂的矩阵的第一行
for(int i=1;i<N;i++)
a[i][i-1]=1; //要求幂的矩阵的其余行
if(m<10) cout<<m%mod;
else
{
fun(a,m-9);
int ans=0;
for(int i=0;i<N;i++)
ans+=res[0][i]*(9-i)%mod;
cout<<ans%mod<<endl;
}
}
return 0;
}