欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

矩阵快速幂 hdu1757

程序员文章站 2022-03-16 18:45:52
...

hdu 1757


#include <iostream>
#include <memory>
typedef long long ll;
using namespace std;
struct matrix
{
    int m[10][10];
};
matrix ans, base, m;
matrix multi(matrix a, matrix b,ll mod)
{
    matrix tmp;
    for (int i = 0; i < 10; ++i)
    {
        for (int j = 0; j < 10; ++j)
        {
            tmp.m[i][j] = 0;
            for (int k = 0; k < 10; ++k)
                tmp.m[i][j] = (tmp.m[i][j] + (a.m[i][k] * b.m[k][j])) % mod;
        }
    }
    return tmp;
}
matrix fastm(matrix base, ll n,ll mod )
{
    int i = 0, j = 0;
    matrix ans;
    memset(ans.m, 0, sizeof(ans.m));
        for (i = 0; i < 10; i++)
            ans.m[i][i] = 1;
    while (n)
    {
        if (n & 1)
        {
            ans = multi(ans, base,mod);
        }
        base = multi(base, base,mod);
        n >>= 1;
    }
    return ans;
}
int main()
{
    ll k,mod, sum ; int i;
    matrix m, ans;
    while (scanf("%I64d%I64d", &k, &mod) == 2)
    {
        sum = 0ll;
        memset(m.m, 0, sizeof(m.m));
        for (i = 1; i < 10; i++)
            m.m[i][i - 1] = 1;//m是系数方阵 
        for (i = 0; i < 10; i++)
            scanf("%d", &m.m[0][i]);
        if (k<10)
        {
            printf("%d\n",k);
            continue;
        }
        k -= 9;
        ans = fastm(m, k,mod);
        for (i = 0; i < 10; i++)
            sum += (ans.m[0][i] * (9 - i)) % mod;
        printf("%d\n", sum%mod);
    }
    return 0;
}
矩阵快速幂 hdu1757

相关标签: 矩阵