C++ – Matrix product

Given two matrices A and B.
The length of A is N1 and the width is M1; the length of B is N2 and the width is M2.

If M1 is equal to N2, matrix product can be performed, and the final result is a matrix of N1 X M2.

#include <cstdio>
using namespace std;
int main() {
    int a11, a12, a13;
    int a21, a22, a23;
    int b11, b12;
    int b21, b22;
    int b31, b32;
    scanf("%d %d %d", &a11, &a12, &a13);
    scanf("%d %d %d", &a21, &a22, &a23);
    scanf("%d %d", &b11, &b12);
    scanf("%d %d", &b21, &b22);
    scanf("%d %d", &b31, &b32);
    printf("%d %d \n", a11 * b11 + a12 * b21 + a13 * b31, 
               a11 * b12 + a12 * b22 + a13 * b32);
    printf("%d %d \n", a21 * b11 + a22 * b21 + a23 * b31, 
               a21 * b12 + a22 * b22 + a23 * b32);
    return 0;
}

Basic operations

Question link

#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 12;
struct Mat {
    int mat[MAXN][MAXN];
    int n, m;
    Mat operator * (const Mat &b) const {
        Mat a = *this;
        Mat ans;
        ans.n = a.n;
        ans.m = b.m;
        memset(ans.mat, 0, sizeof ans.mat);
        for(int i = 0; i < ans.n; i++) 
            for(int j = 0; j < ans.m; j++) 
                for(int k = 0; k < a.m; k++) 
                    ans.mat[i][j] += a.mat[i][k] * b.mat[k][j];
        return ans;
    }
    void scan() {
        for(int i = 0; i < n; i++)
            for(int j = 0; j < m; j++)
                scanf("%d", &mat[i][j]);
    }
    void print() {
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                printf("%d ", mat[i][j]);
            }
            printf("\n");
        }
    }
    Mat qpow(int k) {
        Mat ans;
        ans.n = n;
        ans.m = m;
        for(int i = 0; i < ans.n; i++) {
            for(int j = 0; j < ans.m; j++) {
                ans.mat[i][j] = (i == j);
            }
        }
        while(k) {
            if(k & 1)
                ans = ans * *this;
            *this = *this * *this;
            k >>= 1;
        }
        return ans;
    }
};
int main() {
    Mat m;
    int n, k;
    scanf("%d %d", &n, &k);
    m.n = m.m = n;
    m.scan();
    Mat ans = m.qpow(k);
    ans.print();
    return 0;
}

Post Reply