用c语言利用稀疏矩阵三元组存储实现矩阵的相加算法和转置算法
时间: 2023-12-01 10:03:56 浏览: 137
矩阵相加算法:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int row;
int col;
int val;
} Triple;
void matrix_add(Triple a[], int a_len, Triple b[], int b_len, Triple c[], int *c_len) {
if (a_len == 0 && b_len == 0) {
*c_len = 0;
return;
}
if (a_len == 0) {
*c_len = b_len;
for (int i = 0; i < b_len; i++) {
c[i] = b[i];
}
return;
}
if (b_len == 0) {
*c_len = a_len;
for (int i = 0; i < a_len; i++) {
c[i] = a[i];
}
return;
}
if (a[0].row > b[0].row || (a[0].row == b[0].row && a[0].col > b[0].col)) {
matrix_add(b, b_len, a, a_len, c, c_len);
return;
}
int i = 0, j = 0, k = 0;
while (i < a_len && j < b_len) {
if (a[i].row < b[j].row || (a[i].row == b[j].row && a[i].col < b[j].col)) {
c[k++] = a[i++];
} else if (a[i].row > b[j].row || (a[i].row == b[j].row && a[i].col > b[j].col)) {
c[k++] = b[j++];
} else {
int val = a[i].val + b[j].val;
if (val != 0) {
c[k].row = a[i].row;
c[k].col = a[i].col;
c[k].val = val;
k++;
}
i++;
j++;
}
}
while (i < a_len) {
c[k++] = a[i++];
}
while (j < b_len) {
c[k++] = b[j++];
}
*c_len = k;
}
int main() {
Triple a[3] = {{0, 0, 1}, {1, 1, 2}, {2, 2, 3}};
int a_len = 3;
Triple b[3] = {{0, 0, 1}, {1, 1, 2}, {2, 2, 3}};
int b_len = 3;
Triple c[6];
int c_len;
matrix_add(a, a_len, b, b_len, c, &c_len);
for (int i = 0; i < c_len; i++) {
printf("(%d, %d, %d)\n", c[i].row, c[i].col, c[i].val);
}
return 0;
}
```
矩阵转置算法:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int row;
int col;
int val;
} Triple;
void matrix_transpose(Triple a[], int a_len, Triple b[], int *b_len, int m, int n) {
if (a_len == 0) {
*b_len = 0;
return;
}
int num[m], cpot[m];
for (int i = 0; i < m; i++) {
num[i] = 0;
}
for (int i = 0; i < a_len; i++) {
num[a[i].col]++;
}
cpot[0] = 0;
for (int i = 1; i < m; i++) {
cpot[i] = cpot[i - 1] + num[i - 1];
}
for (int i = 0; i < a_len; i++) {
int j = cpot[a[i].col]++;
b[j].row = a[i].col;
b[j].col = a[i].row;
b[j].val = a[i].val;
}
*b_len = a_len;
}
int main() {
Triple a[3] = {{0, 0, 1}, {1, 1, 2}, {2, 2, 3}};
int a_len = 3;
Triple b[3];
int b_len;
matrix_transpose(a, a_len, b, &b_len, 3, 3);
for (int i = 0; i < b_len; i++) {
printf("(%d, %d, %d)\n", b[i].row, b[i].col, b[i].val);
}
return 0;
}
```
阅读全文