设A和B是两个n*n阶的矩阵,用分治法求他们的乘积矩阵C。使用Strassen算法。C++代码
时间: 2023-11-26 11:03:07 浏览: 106
```
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> strassen(vector<vector<int>>& A, vector<vector<int>>& B) {
int n = A.size();
vector<vector<int>> C(n, vector<int>(n));
if (n == 1) {
C[0][0] = A[0][0] * B[0][0];
return C;
}
vector<vector<int>> A11(n/2, vector<int>(n/2)), A12(n/2, vector<int>(n/2)), A21(n/2, vector<int>(n/2)), A22(n/2, vector<int>(n/2));
vector<vector<int>> B11(n/2, vector<int>(n/2)), B12(n/2, vector<int>(n/2)), B21(n/2, vector<int>(n/2)), B22(n/2, vector<int>(n/2));
vector<vector<int>> S1(n/2, vector<int>(n/2)), S2(n/2, vector<int>(n/2)), S3(n/2, vector<int>(n/2)), S4(n/2, vector<int>(n/2)), S5(n/2, vector<int>(n/2)), S6(n/2, vector<int>(n/2)), S7(n/2, vector<int>(n/2)), S8(n/2, vector<int>(n/2)), S9(n/2, vector<int>(n/2)), S10(n/2, vector<int>(n/2));
vector<vector<int>> P1(n/2, vector<int>(n/2)), P2(n/2, vector<int>(n/2)), P3(n/2, vector<int>(n/2)), P4(n/2, vector<int>(n/2)), P5(n/2, vector<int>(n/2)), P6(n/2, vector<int>(n/2)), P7(n/2, vector<int>(n/2));
// 分解A、B
for (int i = 0; i < n/2; i++) {
for (int j = 0; j < n/2; j++) {
A11[i][j] = A[i][j];
A12[i][j] = A[i][j+n/2];
A21[i][j] = A[i+n/2][j];
A22[i][j] = A[i+n/2][j+n/2];
B11[i][j] = B[i][j];
B12[i][j] = B[i][j+n/2];
B21[i][j] = B[i+n/2][j];
B22[i][j] = B[i+n/2][j+n/2];
}
}
// 计算S、P
S1 = B12 - B22;
P1 = strassen(A11, S1);
S2 = A11 + A12;
P2 = strassen(S2, B22);
S3 = A21 + A22;
P3 = strassen(S3, B11);
S4 = B21 - B11;
P4 = strassen(A22, S4);
S5 = A11 + A22;
S6 = B11 + B22;
P5 = strassen(S5, S6);
S7 = A12 - A22;
S8 = B21 + B22;
P6 = strassen(S7, S8);
S9 = A11 - A21;
S10 = B11 + B12;
P7 = strassen(S9, S10);
// 计算C
vector<vector<int>> C11(n/2, vector<int>(n/2)), C12(n/2, vector<int>(n/2)), C21(n/2, vector<int>(n/2)), C22(n/2, vector<int>(n/2));
C11 = P5 + P4 - P2 + P6;
C12 = P1 + P2;
C21 = P3 + P4;
C22 = P5 + P1 - P3 - P7;
// 合并C
for (int i = 0; i < n/2; i++) {
for (int j = 0; j < n/2; j++) {
C[i][j] = C11[i][j];
C[i][j+n/2] = C12[i][j];
C[i+n/2][j] = C21[i][j];
C[i+n/2][j+n/2] = C22[i][j];
}
}
return C;
}
int main() {
int n;
cout << "请输入矩阵的阶数n:";
cin >> n;
vector<vector<int>> A(n, vector<int>(n)), B(n, vector<int>(n));
cout << "请输入矩阵A:" << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> A[i][j];
}
}
cout << "请输入矩阵B:" << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> B[i][j];
}
}
vector<vector<int>> C = strassen(A, B);
cout << "矩阵C为:" << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << C[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
阅读全文