CSP-202305-2-矩阵运算:题目链接
知识点一:申请矩阵
1.动态分配
// 申请
int** dynamicArray = new int*[rows];
for (int i = 0; i < rows; ++i) {dynamicArray[i] = new int[cols];
}// 释放
for (int i = 0; i < rows; ++i) {delete[] dynamicArray[i];
}
delete[] dynamicArray;
2.静态分配
const int N = 10010, D = 30;
int Array[N][D];
知识点二:矩阵乘法
void matrixMultiplication(long long** A, int rowsA, int colsA, long long** B, int rowsB, int colsB, long long** result) {for (int i = 0; i < rowsA; ++i) {for (int j = 0; j < colsB; ++j) {result[i][j] = 0;for (int k = 0; k < colsA; ++k) {result[i][j] += A[i][k] * B[k][j];}}}
}
难点
1.时间复杂度
- 若直接按照原题给出的
(W⋅(Q×KT))×V
计算,由于Q×KT
的结果为3*3
的矩阵,会显示超时,进而需要改变矩阵的计算顺序,所以要先计算KT*V
(结果为2*2
)的矩阵,可以通过。
2.long long替换int
- 防止由于个别数字的大小超过int的范围。
代码
#include <iostream>
using namespace std;void matrixMultiplication(long long** A, int rowsA, int colsA, long long** B, int rowsB, int colsB, long long** result) {for (int i = 0; i < rowsA; ++i) {for (int j = 0; j < colsB; ++j) {result[i][j] = 0;for (int k = 0; k < colsA; ++k) {result[i][j] += A[i][k] * B[k][j];}}}
}int main() {int row, col;cin >> row >> col;// 动态分配二维数组long long** Q = new long long* [row];long long** K_T = new long long* [col];long long** V = new long long* [row];long long** W = new long long* [1];for (int i = 0; i < row; i++) {Q[i] = new long long[col];V[i] = new long long[col];}for (int i = 0; i < col; i++){K_T[i] = new long long[row];}for (int i = 0; i < 1; i++){W[i] = new long long[row];}// 输入for (int i = 0; i < row; i++){for (int j = 0; j < col; j++){cin >> Q[i][j];}}for (int i = 0; i < row; i++){for (int j = 0; j < col; j++){cin >> K_T[j][i];}}for (int i = 0; i < row; i++){for (int j = 0; j < col; j++){cin >> V[i][j];}}for (int i = 0; i < row; i++){cin >> W[0][i];}// result1 = K_T * V (2*3 * 3*2 = 2*2)long long** result1 = new long long* [col];for (int i = 0; i < col; i++){result1[i] = new long long[col];}matrixMultiplication(K_T, col, row, V, row, col, result1);// result2 = Q * result1long long** result2 = new long long* [row];for (int i = 0; i < row; i++){result2[i] = new long long[col];}matrixMultiplication(Q, row, col, result1, col, col, result2);// result2 *= Wfor (int i = 0; i < row; i++){for (int j = 0; j < col; j++){result2[i][j] = W[0][i] * result2[i][j];}}// 输出for (int i = 0; i < row; i++){for (int j = 0; j < col; j++){cout << result2[i][j] << " ";}cout << endl;}// 释放动态分配的内存for (int i = 0; i < row; i++) {delete[] Q[i];delete[] V[i];delete[] result2[i];}for (int i = 0; i < col; i++) {delete[] K_T[i];delete[] result1[i];}delete[] Q;delete[] K_T;delete[] V;delete[] W[0]; delete[] W;delete[] result2;delete[] result1;return 0;
}