编写算法,实现三元组表表示的两个稀疏矩阵的加法,c语言
时间: 2024-02-18 18:05:56 浏览: 66
以下是实现稀疏矩阵加法的 C 语言代码,其中使用三元组表表示稀疏矩阵:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_TERMS 101
typedef struct {
int row, col, value;
} term;
void sparse_add(term a[], term b[], term c[]) {
int i = 1, j = 1, k = 0;
while (i <= a[0].value && j <= b[0].value) {
if (a[i].row < b[j].row) {
c[++k] = a[i++];
} else if (a[i].row > b[j].row) {
c[++k] = b[j++];
} else {
if (a[i].col < b[j].col) {
c[++k] = a[i++];
} else if (a[i].col > b[j].col) {
c[++k] = b[j++];
} else {
c[++k].row = a[i].row;
c[k].col = a[i].col;
c[k].value = a[i++].value + b[j++].value;
}
}
}
while (i <= a[0].value) {
c[++k] = a[i++];
}
while (j <= b[0].value) {
c[++k] = b[j++];
}
c[0].row = a[0].row;
c[0].col = a[0].col;
c[0].value = k;
}
int main() {
int m1, n1, m2, n2;
printf("Enter the rows and columns of first matrix: ");
scanf("%d%d", &m1, &n1);
printf("Enter the rows and columns of second matrix: ");
scanf("%d%d", &m2, &n2);
if (n1 != m2) {
printf("Matrices cannot be added!\n");
return 0;
}
term a[MAX_TERMS], b[MAX_TERMS], c[MAX_TERMS];
printf("Enter the first matrix:\n");
a[0].row = m1;
a[0].col = n1;
int cnt = 0;
for (int i = 1; i <= m1; i++) {
for (int j = 1; j <= n1; j++) {
int x;
scanf("%d", &x);
if (x != 0) {
a[++cnt].row = i;
a[cnt].col = j;
a[cnt].value = x;
}
}
}
a[0].value = cnt;
printf("Enter the second matrix:\n");
b[0].row = m2;
b[0].col = n2;
cnt = 0;
for (int i = 1; i <= m2; i++) {
for (int j = 1; j <= n2; j++) {
int x;
scanf("%d", &x);
if (x != 0) {
b[++cnt].row = i;
b[cnt].col = j;
b[cnt].value = x;
}
}
}
b[0].value = cnt;
sparse_add(a, b, c);
printf("The result matrix:\n");
for (int i = 1; i <= c[0].value; i++) {
printf("%d %d %d\n", c[i].row, c[i].col, c[i].value);
}
return 0;
}
```
该算法的时间复杂度为 $O(m_1n_1+m_2n_2)$,其中 $m_1,n_1$ 和 $m_2,n_2$ 分别是两个稀疏矩阵的行列数。
阅读全文