hdu 1757 矩阵连乘

来源:互联网 发布:js 获取ios系统版本号 编辑:程序博客网 时间:2024/05/21 09:52

http://acm.hdu.edu.cn/showproblem.php?pid=1757

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 99991 1 1 1 1 1 1 1 1 120 5001 0 1 0 1 0 1 0 1 0
 

Sample Output
45104

#include <stdio.h>#include <iostream>#include <string.h>#include <math.h>using namespace std;typedef long long LL;const int N=10;LL MOD,n;int a[10];struct Matrix{    LL m[N][N];};Matrix I={    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,    0,0,0,0,0,0,0,0,0,1};Matrix multi(Matrix a,Matrix b){    Matrix c;    for(int i=0; i<N; i++)        for(int j=0; j<N; j++)        {            c.m[i][j]=0;            for(int k=0; k<N; k++)            {                c.m[i][j]+=a.m[i][k]*b.m[k][j]%MOD;            }            c.m[i][j]=c.m[i][j]%MOD;        }    return c;}Matrix quick_mod(Matrix a,LL k){    Matrix ans=I;    while(k!=0)    {        if(k&1)        {            ans=multi(ans,a);        }        k>>=1;        a=multi(a,a);    }    return ans;}int main(){    while(~scanf("%I64d%I64d",&n,&MOD))    {        for(int i=0;i<10;i++)            scanf("%d",&a[i]);        if(n<=9)        {            printf("%I64d\n",n);            continue;        }        Matrix A={a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],                    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                    };        Matrix P=quick_mod(A,n-9);        LL x=(P.m[0][0]*9%MOD+P.m[0][1]*8%MOD+P.m[0][2]*7%MOD+P.m[0][3]*6%MOD+P.m[0][4]*5%MOD+P.m[0][5]*4%MOD+P.m[0][6]*3%MOD+P.m[0][7]*2%MOD+P.m[0][8])%MOD;        if(x<0)            x+=MOD;        printf("%I64d\n",x);    }    return 0;}


0 0