A Simple Math Problem
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=10;
ll n,mod;
struct mat
{
ll m[maxn][maxn];
};
mat mat_mul(mat a,mat b) /*矩陣乘法*/
{
mat res;
memset(res.m,0,sizeof(res.m));
for(ll k=0;k<maxn;k++)
{
for(ll i=0;i<maxn;i++)
{
if(!a.m[i][k])
{
continue;
}
for(ll j=0;j<maxn;j++)
{
if(!b.m[k][j])
{
continue;
}
res.m[i][j]=(res.m[i][j]+a.m[i][k]*b.m[k][j])%mod;
}
}
}
return res;
}
mat mat_pow(mat a,ll b) /**矩陣快速冪**/
{
mat res;
memset(res.m,0,sizeof(res.m));
for(ll i=0;i<maxn;i++) //單位矩陣
{
res.m[i][i]=1;
}
while(b)
{
if(b&1)
{
res=mat_mul(res,a);
}
a=mat_mul(a,a);
b>>=1;
}
return res;
}
int main()
{
while(cin>>n>>mod)
{
mat a;
memset(a.m,0,sizeof(a.m));
for(ll i=0;i<maxn;i++)
{
cin>>a.m[i][0];
}
//按題目說的小於10,和大於10兩個區間
if(n<10)
{
cout<<n<<endl;
}
else
{
for(ll i=1;i<maxn;i++)
{
a.m[i-1][i]=1;
}
a=mat_pow(a,n-9);
ll res=0;
for(int i=0;i<maxn;i++)
{
res=(res+(9-i)*a.m[i][0])%mod;
}
cout<<res<<endl;
}
}
}