Skip to content

04041: 矩阵运算

matrices, http://cs101.openjudge.cn/practice/04041/

矩阵有以下两种运算方式:矩阵乘法和矩阵转置

矩阵乘法的计算方法定义为: 对于矩阵A[m][q]*B[q][n], 相乘的结果为矩阵C[m][n]且对于矩阵C中每一项都有 C[i][j] = A[i][0]*B[0][j] + A[i][1]*B[1][j] + ..... + A[i][q]*B[q][j] 注意只有当前一矩阵A的列数等于后一矩阵B的行数时两个矩阵才能相乘。

矩阵的转置定义为: 交换矩阵C[m][q]中所有的行列元素所得到的矩阵C'[q][m]称为矩阵C的转置矩阵,即C'[i][j]=C[j][i] (1 <= i <= q, 1 <= j <= m)。

现在给定矩阵A和B,请你计算矩阵A*矩阵B的乘积结果的转置矩阵,如果矩阵A和矩阵B不能进行乘法运算则直接计算矩阵A的转置矩阵。

输入

两个矩阵A和B 第一行为矩阵的大小,后面跟着输入矩阵,所有元素都是整数,矩阵的行和列大小不超过100 x1,y1 a00 a01 a02 a10 a11 a12 a20 a21 a22 a30 a31 a32

x2,y2 b00 b01 b02 b03 b04 b10 b11 b12 b13 b14 b20 b21 b22 b23 b24

输出

矩阵C’或A' c00 c01 c02 c03 c04 c10 c11 c12 c13 c14 c20 c21 c22 c23 c24 c30 c31 c32 c33 c34

样例输入

4 3
1 2 3
4 5 6
7 8 9
10 11 12
3 5
7 8 9 10 11
4 5 6 7 8
1 2 3 4 5

样例输出

18   54   90  126
24   69  114  159
30   84  138  192
36   99  162  225
42  114  186  258

提示

输出格式 cout << setw(5) << c[i][j]; 头文件要包含 < iomanip >

python
import sys

def matrix_transpose(matrix):
    if not matrix:
        return []
    rows, cols = len(matrix), len(matrix[0])
    return [[matrix[j][i] for j in range(rows)] for i in range(cols)]

def matrix_multiply(A, B):
    a_rows, a_cols = len(A), len(A[0])
    b_cols = len(B[0])
    C = [[0] * b_cols for _ in range(a_rows)]
    for i in range(a_rows):
        for j in range(b_cols):
            for k in range(a_cols):
                C[i][j] += A[i][k] * B[k][j]
    return C

def print_matrix(matrix):
    for row in matrix:
        print(''.join(f'{num:5}' for num in row))

def main():
    # Read matrix A
    x1, y1 = map(int, input().split())
    A = [list(map(int, input().split())) for _ in range(x1)]
    
    # Read matrix B
    x2, y2 = map(int, input().split())
    B = [list(map(int, input().split())) for _ in range(x2)]
    
    # Calculate A * B if possible, else transpose A
    if y1 == x2:
        C = matrix_multiply(A, B)
        result = matrix_transpose(C)
    else:
        result = matrix_transpose(A)
    
    # Output the result matrix
    print_matrix(result)

if __name__ == "__main__":
    main()