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<bits/stdc++.h>
#define LL long long
using namespace std;
const int MAXN = 20;
const int MAXM = 1e6;
const int inf=0x3f3f3f3f;
LL mod,n;
struct Matrix {
LL a[MAXN][MAXN];
int h,w;
}ori,res,it;
LL f[20]={0,1,2,3,4,5,6,7,8,9};
LL a[20];
void init(){
res.h=res.w=10;
memset(res.a,0,sizeof(res.a));
for(int i=1;i<=10;i++) res.a[i][i]=1;
ori.h=ori.w=10;
memset(ori.a,0,sizeof(ori.a));
for(int i=1;i<=10;i++) ori.a[i][1]=a[i];
for(int i=1;i<=9;i++) ori.a[i][i+1]=1;
// 如果想看,可以直接去掉注释
// puts("res ;");
// for(int i=1;i<=10;i++) {//输出 单位矩阵
// for(int j=1;j<=10;j++)
// printf("%lld ",res.a[i][j]);
// puts("");
// }
// puts("ori ;");
// for(int i=1;i<=10;i++) {//输出过渡矩阵
// for(int j=1;j<=10;j++)
// printf("%lld ",ori.a[i][j]);
// puts("");
// }
// puts("it ;"); // 输出原始矩阵
// for(int i=1;i<=1;i++) {
// for(int j=1;j<=10;j++)
// printf("%lld ",it.a[i][j]);
// puts("");
// }
}
Matrix multi(Matrix x,Matrix y){
Matrix z;
z.h=x.h;z.w=y.w;memset(z.a,0,sizeof(z.a));
for(int i=1;i<=x.h;i++){
for(int k=1;k<=x.w;k++){
if(x.a[i][k]==0) continue;
for(int j=1;j<=y.w;j++){
z.a[i][j]=(z.a[i][j]+x.a[i][k]*y.a[k][j]%mod)%mod;
}
}
}
return z;
}
void Matrix_mod(int n){
while(n){
if(n&1) res=multi(ori,res);
ori=multi(ori,ori);
n>>=1;
}
res=multi(it,res);
printf("%lld\n",res.a[1][1]%mod);
}
int main(){
it.h=1;it.w=10;
for(int i=10;i>=1;i--) it.a[1][i]=f[10-i];
while(scanf("%lld%lld",&n,&mod)!=EOF){
for(int i=1;i<=10;i++){
scanf("%lld",&a[i]);
}
init();
if(n<10) printf("%lld\n",f[n]%mod);
else Matrix_mod(n-9);
}
return 0;
}