首页 > 其他 > 详细

矩阵类模板

时间:2020-05-30 23:19:08      阅读:43      评论:0      收藏:0      [点我收藏+]

矩阵类,支持矩阵的加减乘和幂运算

const int MAXN = 105;
const int MAXM = 105;
struct Martix
{
    int n, m;                    //n:矩阵行数         m:矩阵列数
    int a[MAXN][MAXM];
    void clear() {            //清空矩阵
        n = m = 0;
        memset(a, 0, sizeof(a));
    }
    Martix operator+(const Martix& b) const {
        Martix tmp;
        tmp.n = n; tmp.m = m;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                tmp.a[i][j] = a[i][j] + b.a[i][j];
        return tmp;
    }
    Martix operator-(const Martix& b) const {
        Martix tmp;
        tmp.n = n; tmp.m = m;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                tmp.a[i][j] = a[i][j] - b.a[i][j];
        return tmp;
    }
    Martix operator*(const Martix& b) const {
        Martix tmp;
        tmp.clear();
        tmp.n = n; tmp.m = b.m;
        for (int i = 0; i < tmp.n; i++)
            for (int j = 0; j < tmp.m; j++) 
                for (int k = 0; k < m; k++) {
                    tmp.a[i][j] += a[i][k] * b.a[k][j];
                    tmp.a[i][j] %= mod;
                }
        return tmp;
    }
    Martix operator^(int x)const {
        Martix base, ans;
        base = *this; 
        ans.clear(); ans.m = ans.n = n;
        for (int i = 0; i < n; i++) ans.a[i][i] = 1;
        if (x == 0) return ans;
        if (x == 1) return base;
        while (x) {
            if (x & 1) ans = ans * base;
            base = base * base;
            x >>= 1;
        }
        return ans;
    }
};

 

矩阵类模板

原文:https://www.cnblogs.com/jaszzz/p/12995245.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!