A Simple Math Problem
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
矩阵快速幂详解:链接
矩阵快速幂方法(模板):
#include<iostream>
#include<cstring>
using namespace std;
typedef long long LL;
const int maxn = 15;
struct Matrix{
LL matrix[maxn][maxn];
}ori, ans;//ori矩阵存放幂运算结果,ans存放结果
int n=10, k, m;
void init()//初始化工作
{
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
ori.matrix[i][j] = ans.matrix[i][j] = 0;
for(int i=0;i<n;i++)
{
cin>>ori.matrix[0][i];
ori.matrix[i+1][i] = 1;
ans.matrix[i][0] = 9-i;
}
}
//矩阵相乘
Matrix multiply(Matrix a, Matrix b)
{
Matrix temp;
memset(temp.matrix, 0, sizeof(temp.matrix));
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
for(int k=0;k<n;k++)
temp.matrix[i][j] = (temp.matrix[i][j] % m + (a.matrix[i][k] % m * b.matrix[k][j] % m) % m) % m;
return temp;
}
//矩阵的b次幂
Matrix binaryPow(int b)
{
Matrix temp;
memset(temp.matrix, 0, sizeof(temp.matrix));
for(int i=0;i<n;i++)
temp.matrix[i][i] = 1;
while(b > 0)
{
if(b & 1)
temp = multiply(temp, ori);
ori = multiply(ori, ori);
b >>= 1;
}
return temp;
}
int main()
{
//freopen("in.txt", "r", stdin);
while(cin>>k>>m)
{
if(k < n)
{
cout<<k<<endl;
continue;
}
init();
Matrix temp = binaryPow(k-9);//矩阵的k-9次幂
ans = multiply(temp, ans);
cout<<ans.matrix[0][0]<<endl;
}
return 0;
}