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
思路:这个是矩阵快速幂,没看出来的话不好做要是看出来就很好做了。
关系矩阵是 a0 a1 a2 a3 a4 a5 a6 a7 a8 a9
1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 1 0
(矩阵快速幂一直不会写,只会直接粘贴代码 - -)
#include <iostream>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <cmath>
#include <list>
#include <queue>
#include <stack>
#include <map>
#include <set>
using namespace std;
int n;
long long k,m;
int N;
struct node{long long a[11][11];};
node shu,ans,mp;
node matrix(node x,node y){
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++){
mp.a[i][j]=0;
for(int p=1;p<=n;p++)
mp.a[i][j]=(mp.a[i][j]+x.a[i][p] * y.a[p][j])%N;
}
return mp;
}
void work(long long k){
while(k){
if(k&1)
ans=matrix(ans,shu);
k>>=1;
shu=matrix(shu,shu);
}
}
int main(){
while(~scanf("%lld%d",&k,&N))
{
n=10;
// sum=0;
memset(ans.a,0,sizeof(ans.a));
memset(shu.a,0,sizeof(shu.a));
for(int i=1;i<=n;i++){
ans.a[i][i]=1;
}
for(int i=1;i<=n;i++)
{
cin>>shu.a[1][i];
}
int t=1;
for(int i=2;i<=n;i++)
{
shu.a[i][t]=1;
t++;
}
work(k-9);
long long sum=0;
t=9;
for(int i=1;i<=n;i++){
sum+=ans.a[1][i]*t;
sum=sum%N;
t--;
}
cout<<sum<<endl;
}
return 0;
}