用c++编写对于两个 n×n 的矩阵 A 和 B,计算 C=A×B。采用分治法设计实现更有效的算法.代码
时间: 2024-10-25 08:03:27 浏览: 20
01_比较矩阵相乘的常规法和Strassen方法.zip_01矩阵算法_C++_VS2012
在C++中,为了实现两个n×n矩阵A和B的乘法运算,并利用分治法提高效率,我们通常会采用Strassen's Matrix Multiplication算法,它是一种分治策略的应用。这个算法将一个大问题分解成4个规模较小的问题和7个常数大小的子矩阵相加,减少了基本乘法次数。以下是简单的示例代码:
```cpp
#include <vector>
using namespace std;
// 基本的矩阵乘法
vector<vector<int>> matrixMultiply(vector<vector<int>>& A, vector<vector<int>>& B, int n) {
vector<vector<int>> result(n, vector<int>(n, 0));
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j) {
for (int k = 0; k < n; ++k)
result[i][j] += A[i][k] * B[k][j];
}
return result;
}
// Strassen's Matrix Multiplication递归函数
vector<vector<int>> strassen(int m, int n, vector<vector<int>>& A, vector<vector<int>>& B) {
if (m == 1 || n == 1) return matrixMultiply(A, B, min(m, n));
int sqrtN = sqrt(n);
// 分割矩阵
vector<vector<int>> a11, a12, a21, a22, b11, b12, b21, b22;
for (int i = 0; i < sqrtN; ++i) {
for (int j = 0; j < sqrtN; ++j) {
a11 = {A[i][j], A[i][j + sqrtN]};
a12 = {A[i + sqrtN][j], A[i + sqrtN][j + sqrtN]};
a21 = {A[i][n - j - sqrtN], A[i][n - j]};
a22 = {A[i + sqrtN][n - j - sqrtN], A[i + sqrtN][n - j]};
b11 = {B[j][j], B[j][j + sqrtN]};
b12 = {B[j + sqrtN][j], B[j + sqrtN][j + sqrtN]};
b21 = {B[n - j - sqrtN][j], B[n - j - sqrtN][j + sqrtN]};
b22 = {B[n - j][j], B[n - j][j + sqrtN]};
// 计算子矩阵
vector<vector<int>> temp(4, vector<int>(4, 0));
temp[0] = strassen(sqrtN, sqrtN, a11 + a22, b22 - b12); // P1
temp[1] = strassen(sqrtn, sqrtN, a21, b11 - b21); // P2
temp[2] = strassen(sqrtn, sqrtN, a11 - a22, b11 + b22); // P3
temp[3] = strassen(sqrtn, sqrtN, a21 + a22, b12 + b22); // P4
// 将结果组合起来
a22 = temp[1]; // R1 = P2
a21 = temp[3] - a22; // R2 = P4 - R1
a11 = temp[0] + a22; // R3 = P1 + R2
a12 = temp[2] - a11; // R4 = P3 - R3
b22 = temp[2] + temp[3]; // S1 = P3 + P4
b21 = temp[0] - temp[1]; // S2 = P1 - P2
b11 = temp[1] + temp[2]; // S3 = P2 + P3
b12 = temp[0] + temp[3]; // S4 = P1 + P4
}
}
// 重构最终结果矩阵
int offset = (sqrtN - 1) * sqrtN / 2;
for (int i = 0; i < sqrtN; ++i) {
for (int j = 0; j < sqrtN; ++j) {
result[i][j] = a11[i][j] + a12[i][j] + a21[i][j + sqrtN] + a22[i][j + sqrtN];
result[i][j + sqrtN] = b21[i][j] + b22[i][j];
result[i + sqrtN][j] = b11[i][j] + b12[i][j];
result[i + sqrtN][j + sqrtN] = a21[i][j] + a22[i][j] - b11[i][j] - b12[i][j];
}
}
return result;
}
int main() {
// 请在这里替换实际的矩阵A和B数据
int n = 4;
vector<vector<int>> A(n, vector<int>(n)), B(n, vector<int>(n));
// ...
vector<vector<int>> result = strassen(n, n, A, B);
// 打印结果矩阵
// ...
return 0;
}
```
阅读全文