矩阵快速幂模板

#include
#include
#include
using namespace std;
const int N = 66;
struct Matrix
{
    int a[N][N];
};
Matrix Mul(Matrix ans, Matrix res, int n, int mod)
{
    Matrix C;
    memset(C.a, 0, sizeof(C.a));
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            for (int k = 0; k < n; k++)
            {
                C.a[i][j] = (C.a[i][j] + (ans.a[i][k] * res.a[k][j]) % mod) % mod;
            }
        }
    }
    return C;
}
Matrix QuickPower(Matrix res, int k, int n, int mod)
{
    Matrix ans;
    memset(ans.a, 0, sizeof(ans.a));
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            if (i == j)
            {
                ans.a[i][j] = 1;
            }
        }
    }
    while (k)
    {
        if (k & 1)
        {
            ans = Mul(ans, res, n, mod);
        }
        res = Mul(res, res, n, mod);
        k = k >> 1;
    }
    return ans;
}

 

你可能感兴趣的:(矩阵快速幂模板)