稀疏矩阵三元组乘法c语言完整代码
时间: 2024-10-19 22:02:00 浏览: 32
稀疏矩阵三元组乘法是一种优化的矩阵乘法算法,适用于矩阵中大部分元素为0的情况。以下是一个简单的稀疏矩阵三元组乘法的C语言完整代码:
```
#include <stdio.h>
#define MAX_SIZE 100
typedef struct {
int row;
int col;
int val;
} Triple;
void sparseMatrixMultiply(Triple A[], Triple B[], Triple C[]) {
int i, j, k, sum;
int flag[MAX_SIZE] = {0};
int num = 0;
for (i = 0; i < MAX_SIZE; i++) {
sum = 0;
for (k = 0; k < MAX_SIZE; k++) {
flag[k] = 0;
}
for (k = 0; A[k].row <= i && k < MAX_SIZE; k++) {
if (A[k].row == i) {
flag[A[k].col] = A[k].val; }
}
for (j = 0; j < MAX_SIZE; j++) {
if (flag[j] != 0) {
for (k = 0; B[k].row <= j && k < MAX_SIZE; k++) {
if (B[k].row == j && B[k].col == i) {
sum += flag[j] * B[k].val;
}
}
}
}
if (sum != 0) {
C[num].row = i;
C[num].col = j;
C[num].val = sum;
num++;
}
}
}
int main() {
Triple A[MAX_SIZE] = {{0, 0, 1}, {0, 1, 0}, {0, 3, 3}, {1, 2, 2}, {2, 1, 4}, {3, 0, 5}};
Triple B[MAX_SIZE] = {{0, 1, 2}, {1, 2, 1}, {2, 0, 3}, {2, 1, 4}, {3, 0, 5}};
Triple C[MAX_SIZE];
sparseMatrixMultiply(A, B, C);
int i;
for (i = 0; i < MAX_SIZE; i++) {
printf("%d %d %d\n", C[i].row, C[i].col, C[i].val);
}
return 0;
}
```
阅读全文