使用分治法实现矩阵乘法的C++代码
时间: 2024-05-07 18:16:07 浏览: 143
```
#include <stdio.h>
#define N 3
void matrix_multiply(int A[][N], int B[][N], int C[][N], int n) {
if (n == 1) {
C[0][0] = A[0][0] * B[0][0];
return;
}
int A11[N/2][N/2], A12[N/2][N/2], A21[N/2][N/2], A22[N/2][N/2];
int B11[N/2][N/2], B12[N/2][N/2], B21[N/2][N/2], B22[N/2][N/2];
int C11[N/2][N/2], C12[N/2][N/2], C21[N/2][N/2], C22[N/2][N/2];
int P[N/2][N/2], Q[N/2][N/2], R[N/2][N/2], S[N/2][N/2], T[N/2][N/2], U[N/2][N/2], V[N/2][N/2];
int i, j, k;
// 将矩阵 A 和 B 分成四个子矩阵
for (i = 0; i < N/2; i++) {
for (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];
}
}
// 计算七个矩阵乘积
matrix_multiply(A11, B11, P, N/2);
matrix_multiply(A12, B21, Q, N/2);
matrix_multiply(A11, B12, R, N/2);
matrix_multiply(A12, B22, S, N/2);
matrix_multiply(A21, B11, T, N/2);
matrix_multiply(A22, B21, U, N/2);
matrix_multiply(A21, B12, V, N/2);
// 计算 C11, C12, C21, C22
for (i = 0; i < N/2; i++) {
for (j = 0; j < N/2; j++) {
C11[i][j] = P[i][j] + Q[i][j];
C12[i][j] = R[i][j] + S[i][j];
C21[i][j] = T[i][j] + U[i][j];
C22[i][j] = V[i][j] + P[i][j] - R[i][j] - T[i][j];
}
}
// 将 C11, C12, C21, C22 合并为 C
for (i = 0; i < N/2; i++) {
for (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];
}
}
}
int main() {
int A[N][N] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int B[N][N] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int C[N][N];
matrix_multiply(A, B, C, N);
int i, j;
printf("C = \n");
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
printf("%d ", C[i][j]);
}
printf("\n");
}
return 0;
}
```
阅读全文