【HDU 1757】 A Simple Math Problem

2020-05-31 23:40:16 浏览数 (1)

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

题意:按f(x) = a0 * f(x-1) a1 * f(x-2) a2 * f(x-3) …… a9 * f(x-10) (x>=10) ; f(x) = x(x<10)来计算f(x)%m的值。

分析:这题要用递推,并且k值很大,所以需要用矩阵快速幂。

构造的矩阵是:

a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 1                     1                     1                     1                     1                     1                     1                     1                     1

a0

a1

a2

a3

a4

a5

a6

a7

a8

a9

1

1

1

1

1

1

1

1

1

*

f(x-1) f(x-2) f(x-3) f(x-4) f(x-5) f(x-6) f(x-7) f(x-8) f(x-9) f(x-10)

f(x-1)

f(x-2)

f(x-3)

f(x-4)

f(x-5)

f(x-6)

f(x-7)

f(x-8)

f(x-9)

f(x-10)

=

f(x) f(x-1) f(x-2) f(x-3) f(x-4) f(x-5) f(x-6) f(x-7) f(x-8) f(x-9)

f(x)

f(x-1)

f(x-2)

f(x-3)

f(x-4)

f(x-5)

f(x-6)

f(x-7)

f(x-8)

f(x-9)

a0

a1

a2

a3

a4

a5

a6

a7

a8

a9

1

1

1

1

1

1

1

1

1

f(x-1)

f(x-2)

f(x-3)

f(x-4)

f(x-5)

f(x-6)

f(x-7)

f(x-8)

f(x-9)

f(x-10)

f(x)

f(x-1)

f(x-2)

f(x-3)

f(x-4)

f(x-5)

f(x-6)

f(x-7)

f(x-8)

f(x-9)

写个结构类型代表矩阵,以及矩阵的相乘的函数和矩阵快速幂的函数,注意一下初始化。

代码语言:javascript复制
#include<stdio.h>
#include<string.h>
int n,k,m;
struct matrix
{
    int a[15][15];
    int row,col;
    void init(int r,int c){
        memset(a,0,sizeof(a));
        row=r;col=c;
    }
} big,f,u;
matrix mul(matrix a,matrix b)
{
    matrix c;
    c.init(a.row,b.col);
    for(int i=0; i<a.row; i  )
        for(int j=0; j<b.col; j  )
        {
            for(int k=0; k<a.col; k  )
                c.a[i][j] =(a.a[i][k]*b.a[k][j])%m;
            c.a[i][j]%=m;
        }
    return c;
}
void init()
{
    big.init(10,10);
    f.init(10,1);
    for(int i=1; i<10; i  )
        big.a[i][i-1]=1;
    for(int i=0; i<10; i  )
        f.a[i][0]=9-i;
}
matrix qpow(matrix a,int k)
{
    matrix ans;
    ans.init(a.row,a.col);
    for(int i=0;i<a.row;i  )
        ans.a[i][i]=1;
    while(k)
    {
        if(k&1)ans=mul(ans,a);
        a=mul(a,a);
        k>>=1;
    }
    return ans;
}
int main()
{
    init();
    while(~scanf("%d%d",&k,&m))
    {
        for(int i=0; i<10; i  )
            scanf("%d",&big.a[0][i]);
        u=mul(qpow(big,k-9),f);
        printf("%dn",u.a[0][0]%m);
    }
    return 0;
}

0 人点赞