已知两个稀疏矩阵A和B采用三元组顺序表存储,
求:M= A+B、M= A-B和M= A×B。
【测试数据】
A的三元组表为:
(0, 2, -9)(0, 4, 5)(1, 0, -7)(1, 2, 7)(3, 1, 8)(4, 2, 9)
B的三元组表为:
(1, 0, 7)(1, 2, 7)(2, 1, 1)(3, 0, 1)(4, 4, 1)
和:
差:
积:
#include <iostream>
#define M 5
#define N 5
#define MAXSIZE 25
using namespace std;
typedef struct TupNode
{
int r;
int c;
int data;
} Tup;
typedef struct TSMatrix
{
int rows;//整个矩阵的行数
int cols;//整个矩阵的列树
int nums;//三元组中储存的元素个数,其实就代表着矩阵中的非零元素个数
TupNode arr[MAXSIZE];//三元组本体
} Mat;
Mat *createMat(int (&a)[M][N])//根据传进来的二维数组引用创建三元组
{
Mat *mat = new Mat;
int i, j;
mat->cols = N;
mat->rows = M;
mat->nums = 0;
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
if (a[i][j] != 0)
{
mat->arr[mat->nums].r = i;
mat->arr[mat->nums].c = j;
mat->arr[mat->nums].data = a[i][j];
mat->nums++;
}
}
}
return mat;
}
Mat *createMat(Mat *mat)//根据传进来的三元组创建三元组的拷贝,若传NULL,则返回空三元组
{
Mat *res = new Mat;
res->cols = N;
res->rows = M;
res->nums = 0;
if (mat)
*res = *mat;
return res;
}
int binSearch(Mat *mat, int r, int c, bool returnLastPos, bool *isSucc)
{
int a = 0, b = mat->nums - 1;
int mid;
while (a <= b)
{
mid = (a + b) / 2;
if (mat->arr[mid].r == r && mat->arr[mid].c == c)
{
if (isSucc)
*isSucc = true;
return mid;
}
else if (mat->arr[mid].r < r ||