HDU1757 A Simple Math Problem

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

矩阵

矩阵快速幂加速模板

注意,初始矩阵第一个数是\(f(9)\)而不是\(f(0)\)

如下:

\[\begin{equation} \left[ \begin{array}{c} 9 \\ 8 \\ 7 \\ 6 \\ 5 \\ 4 \\ 3 \\ 2 \\ 1 \\ 0 \\ \end{array} \right] \end{equation} \]

\(C++ Code:\)

#include<cstdio>
#include<iostream>
#include<algorithm>
#define ll long long
using namespace std;
int k;
ll m;
struct matrix
{
    ll a[15][15];
    matrix operator * (matrix b)
    {
        matrix c;
        for (int i=0;i<=10;i++)
            for (int j=0;j<=10;j++)
                c.a[i][j]=0;
        for (int k=1;k<=10;k++)
            for (int i=1;i<=10;i++)
                for (int j=1;j<=10;j++)
                    c.a[i][j]=(c.a[i][j]+a[i][k]*b.a[k][j])%m;
        return c;
    }
}zy,zero,f;
matrix ksm(matrix x,ll y)
{
    matrix ans=zero;
    while (y)
    {
        if (y&1)
            ans=ans*x;
        x=x*x;
        y >>=1;
    }
    return ans;
}
int main()
{
    for (int i=1;i<10;i++)
        zy.a[i+1][i]=1;
    for (int i=1;i<=10;i++)
        zero.a[i][i]=1;
    for (int i=1;i<=10;i++)
        f.a[i][1]=10-i;
    while (scanf("%d%lld",&k,&m)!=EOF)
    {
        for (int i=1;i<=10;i++)
            scanf("%lld",&zy.a[1][i]);
        k++;
        if (k<=10)
        {
            printf("%lld\n",f.a[k][1]);
            continue;
        }
        matrix ans=ksm(zy,k-10)*f;
        cout << ans.a[1][1] << endl;
    }
}
posted @ 2020-07-25 15:53  GK0328  阅读(66)  评论(0编辑  收藏  举报