HDU-1757-A Simple Math Problem

题目传送门
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 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 <cstring>
#include <iostream>
#include <cstdio>
#define  m(a,b) memset(a,b,sizeof a)
typedef long long ll;
using namespace std;
const int N=12;
ll p,mod;
struct mat{ll a[N][N];};
mat mat_mul(mat x,mat y)
{
    mat res;
    m(res.a,0);
    for(int i=1;i<=10;i++)
        for(int j=1;j<=10;j++)
            for(int k=1;k<=10;k++)
                res.a[i][j]=(res.a[i][j]+(x.a[i][k]*y.a[k][j])%mod)%mod;
    return res;
}
mat mat_pow(mat c,ll p)
{
    mat res;
    m(res.a,0);
    for(int i=1;i<=10;i++)
        res.a[i][i]=1;
    while(p)
    {
        if(p&1)
            res=mat_mul(res,c);
        c=mat_mul(c,c);
        p>>=1;
    }
    return res;
}
int main()
{
    while(~scanf("%lld%lld",&p,&mod))
    {
        mat c;
        m(c.a,0);
        for(int i=1;i<=10;i++)
            scanf("%lld",&c.a[1][i]);
        if(p<10)
        {
            printf("%lld\n",p%mod);
            continue;
        }
        for(int i=2;i<=10;i++)
            c.a[i][i-1]=1;
        mat ans=mat_pow(c,p-9);
        ll fin=0;
        for(int i=1;i<=10;i++)
            fin=(fin+ans.a[1][i]*(10-i))%mod;
        printf("%lld\n",fin);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42576687/article/details/87211375
今日推荐