[HDU]A Simple Math Problem
A Simple Math Problem
Time Limit: 3000/1000 MS (Java/Others)
Memory Limit: 32768/32768 K (Java/Others)
Problem Description
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
Author
linle
Source
Recommend
lcy | We have carefully selected several similar problems for you: 1575 1588 3117 2276 2256
思路
矩阵构造+矩阵快速幂
根据题目可以构造一下矩阵乘法:
$$ \left[ \begin{matrix} a0 &a_1 & \cdots & a_8 & a_9 \1 & \ & \ddots\ && \ddots\ & & &1\end{matrix} \right] \times \left[ \begin{matrix} f{x-1} \f{x-2}\ \vdots \f{x-9} \f{x-10} \end{matrix} \right] = \left[ \begin{matrix} f_x\f{x-1}\ \vdots \f{x-8} \ f{x-9} \end{matrix} \right]
$$
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int k,mod;
struct Matrix
{
int a[10][10];
Matrix(){memset(a,0,sizeof(a));}
void mul(Matrix x)
{
Matrix tmp;
for(int i=0;i<10;i++)
for(int j=0;j<10;j++)
for(int k=0;k<10;k++)
{
tmp.a[i][j]+=a[i][k]*x.a[k][j];
if(tmp.a[i][j]>=mod)tmp.a[i][j]%=mod;
}
for(int i=0;i<10;i++)
for(int j=0;j<10;j++)
a[i][j]=tmp.a[i][j];
}
};
int main()
{
while(scanf("%d%d",&k,&mod)==2)
{
Matrix m1,m2;
for(int i=0;i<10;i++)
scanf("%d",&m1.a[0][i]);
if(k<10){printf("%d\n",k);continue;}
for(int i=1;i<10;i++)
m1.a[i][i-1]=1;
m2=m1;
k-=10;
while(k)
{
if(k&1) m1.mul(m2);
m2.mul(m2);
k>>=1;
}
int ans=0;
for(int i=0;i<10;i++)
{
ans+=m1.a[0][i]*(9-i);
if(ans>=mod)ans%=mod;
}
printf("%d\n",ans);
}
}