矩阵快速幂

快速幂

typedef unsigned long long ull;
ull quick_pow(ull a, int p)
{
    ull res = 1;
    while(p)
    {
        if(p&1) res *= a;
        a *= a;
        p >>= 1;
    }
    return res;
}

矩阵的乘法

typedef unsigned long long ull;
typedef vector<ull> vec;
typedef vector<vec> mat;
#define MOD 1000000007
mat mat_mul(mat &a, mat &b)
{
    mat c(a.size(), vec(b[0].size()));
    int m = a.size(), t = a[0].size(), n = b[0].size();
    for(int i = 0; i < m; ++i)
        for(int j = 0; j < n; ++j)
            for(int k = 0; k < t; ++k)
            {
                c[i][j] += a[i][k]*b[k][j];
                c[i][j] %= MOD; // if need
            }
    return c;
}

矩阵快速幂

// 提示:矩阵快速幂必须保证矩阵为方阵
mat mat_pow(mat a, int p)
{
    mat res(a.size(), vec(a.size()));
    for(int i = 0, len = a.size(); i < len; ++i)
        res[i][i] = 1;
    while(p)
    {
        if(p&1) res = mat_mul(res, a);
        a = mat_mul(a, a);
        p >>= 1;
    }
    return res;
}
posted @ 2019-11-20 23:21  silverling  阅读(64)  评论(0)    收藏  举报