//在稀疏矩阵的三元组表存储结构下完成矩阵的加减和转置运算
#include <iostream>
using namespace std;
typedef int ElemType;
const int MAXSIZE = 12500;
typedef struct {
int i, j;//该非零元的行下标和列下标
ElemType e;
} Triple;
typedef struct{
Triple data[MAXSIZE + 1];//非零元三元组表,data[0]未用
int row, col, num; //矩阵的行数,列数,非零元个数
} TSMatrix;
//矩阵的加法
TSMatrix addMatrix(TSMatrix A,TSMatrix B){
TSMatrix C;
if(A.row != B.row || A.col != B.col){
cout << "两个矩阵的行列数不相等" << endl;
C.num = 0;
return C;
}
int i = 0, j = 0, k = 0;
while(i < A.num && j < B.num){
if(A.data[i].i == B.data[j].i && A.data[i].j == B.data[j].j){
C.data[k].i = A.data[i].i;
C.data[k].j = A.data[i].j;
C.data[k].e = A.data[i].e + B.data[j].e;
i++;
j++;
k++;
}else if (A.data[i].i < B.data[j].i || (A.data[i].i == B.data[j].i && A.data[i].j < B.data[j].j))
{
C.data[k].i = A.data[i].i;
C.data[k].j = A.data[i].j;
C.data[k].e = A.data[i].e;
i++;
k++;
}else{
C.data[k].i = B.data[j].i;
C.data[k].j = B.data[j].j;
C.data[k].e = B.data[j].e;
j++;
k++;
}
}
while(i <A.num){
C.data[k].i = A.data[i].i;
C.data[k].j = A.data[i].j;
C.data[k].e = A.data[i].e;
i++;
k++;
}
while(j <B.num){
C.data[k].i = B.data[j].i;
C.data[k].j = B.data[j].j;
C.data[k].e = B.data[j].e;
j++;
k++;
}
C.row = A.row;
C.col = A.col;
C.num = k;
return C;
}
//矩阵的减法
TSMatrix subMaTrix(TSMatrix A,TSMatrix B){
TSMatrix C;
for (int i = 0; i < B.num; i++){
C.data[i].i = B.data[i].i;
C.data[i].j = B.data[i].j;
C.data[i].e = -B.data[i].e;
}
C.row = B.row;
C.col = B.col;
C.num = B.num;
TSMatrix D = addMatrix(A, C);
return D;
}
//矩阵转置
TSMatrix TransposeMaTrix(TSMatrix A){
TSMatrix B;
int arow = A.row, acol = A.col, anum = A.num;
B.row = acol;
B.col = arow;
B.num = anum;
if (anum > 0){
int col, k = 0;
for (col = 1; col <= acol; col ++){
for (int p = 0; p < anum; p ++){
if(A.data[p].j == col){
B.data[k].i = A.data[p].j;
B.data[k].j = A.data[p].i;
B.data[k].e = A.data[p].e;
k++;
}
}
}
}
return B;
}
//打印矩阵
void printMaTrix(TSMatrix A){
int k = 0;
if(A.num> 0){
for (int i = 1; i <= A.row; i++){
for (int j = 1; j <= A.col; j++){
if(A.data[k].i == i && A.data[k].j == j){
cout << A.data[k].e << " ";
k++;
}else{
cout << "0 ";
}
}
cout << endl;
}
}
}
int main() {
TSMatrix A, B, C;
// 初始化矩阵 A
A.row = 3;
A.col = 4;
A.num = 4;
A.data[0].i = 1;
A.data[0].j = 1;
A.data[0].e = 1;
A.data[1].i = 1;
A.data[1].j = 3;
A.data[1].e = 2;
A.data[2].i = 2;
A.data[2].j = 2;
A.data[2].e = 3;
A.data[3].i = 3;
A.data[3].j = 4;
A.data[3].e = 4;
// 初始化矩阵 B
B.row = 3;
B.col = 4;
B.num = 3;
B.data[0].i = 1;
B.data[0].j = 2;
B.data[0].e = 1;
B.data[1].i = 2;
B.data[1].j = 1;
B.data[1].e = 2;
B.data[2].i = 3;
B.data[2].j = 4;
B.data[2].e = 3;
cout << "矩阵 A:" << endl;
printMaTrix(A);
cout << "矩阵 B:" << endl;
printMaTrix(B);
// 矩阵加法
C = addMatrix(A, B);
cout << "矩阵 A + B:" << endl;
printMaTrix(C);
// 矩阵减法
C = subMaTrix(A, B);
cout << "矩阵 A - B:" << endl;
printMaTrix(C);
// 矩阵转置
B = TransposeMaTrix(A);
cout << "矩阵 A 的转置:" << endl;
printMaTrix(B);
return 0;
}
在稀疏矩阵的三元组表存储结构下完成矩阵的加减和转置运算
最新推荐文章于 2023-12-18 10:55:49 发布