稀疏矩阵三元组存储结构的定义及其有关算法的实现

本文详细介绍了稀疏矩阵的三元组存储结构,并提供了C++实现的相关代码,包括矩阵的创建、加法和乘法等算法。
摘要由CSDN通过智能技术生成
 C++ Code jjbran
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
矩阵相加算法: ```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; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值