矩阵快速幂 C++实现

花了两天时间学习了矩阵快速幂和应用(基本就是拿来学应用上了,矩阵快速幂加外就学了五分钟),基本故事就是发现算法几乎一点难度没有(快速幂改变一下就完事了),难的是写完…怎么用啊,然后的故事就是恶补了几个小时的线性代数的知识,从此矩阵快速幂的题目沦为数学题,咳咳,下面是代码

typedef long long LL;
const LL mod = 0;//该处初始化为0为了防止程序员没初始化mod值。
inline LL modadd(LL a,LL b){ return ((a % mod) + (b % mod))  % mod; }
inline LL modsub(LL a,LL b){ return ((a % mod) - (b % mod) + mod) % mod; }
inline LL modmul(LL a,LL b){ return ((a % mod) * (b % mod)) % mod; }
const int MAXN = 4;
template
struct matrix
{
    T base[MAXN][MAXN];
    size_t row,line;
    matrix(size_t row,size_t line){
        this -> row = row;
        this -> line = line;
    }
    matrix(initializer_list > l){
        row = l.size();
        line = l.begin() -> size();
        size_t j = 0;
        auto iter1 = l.begin();
        while(iter1 != l.end())
        {
            size_t k = 0;
            auto iter2 = iter1 -> begin();
            while(iter2 != iter1 -> end())
            {
                base[j][k] = *iter2;
                iter2++,k++;
            }
            iter1++,j++;
        }
    }
    matrix(const matrix & others){
        row = others.row;
        line = others.line;
        for(size_t j = 0;j != row;j++)
            for(size_t k = 0;k != line;k++)
                base[j][k] = others[j][k];
    }
    friend matrix operator * (const matrix & lsh,const matrix & rsh){
        matrix res(lsh.row,rsh.line);
        memset(res.base , 0 ,sizeof(res.base));
        for(size_t q = 0;q != lsh.line;q++)
            for(size_t j = 0;j != lsh.row;j++)
                if(lsh[j][q])
                    for(size_t k = 0;k != rsh.line;k++)
                        if(rsh[q][k])
                            res[j][k] = modadd(res[j][k] , modmul(lsh[j][q] , rsh[q][k]));
        return res;
    }
    friend matrix pow(matrix a,LL n){
        matrix res(a.row,a.line);
        memset(res.base , 0 ,sizeof res.base);
        for(size_t j = 0;j != a.row;j++)
            res[j][j] = 1;

        while(n) {
            if(n & 1)
                res = res * a;
            a = a * a;
            n >>= 1;
        }
        return res;
    }
    friend ostream & operator << (ostream & out,const matrix & rsh){
        for(size_t j = 0;j != rsh.line * 2 + 1;j++)
            out << "-";
        out << endl;
        for(size_t j = 0;j != rsh.row;j++)
        {
            for(size_t k = 0;k != rsh.line;k++)
                out << "|" << rsh[j][k];
            out << "|" << endl;
        }
        for(size_t j = 0;j != rsh.line * 2 + 1;j++)
            out << "-";
        out << endl;
        return out;
    }
    T * operator[](size_t pos){
        return base[pos];
    }
    const T * operator[](size_t pos)const{
        return base[pos];
    }
};

你可能感兴趣的:(算法实现)