数组与广义表_稀疏矩阵的压缩存储_三元组做存储结构_矩阵相乘
head.h
#include<iostream>
using namespace std;
#define MAX_MATRIXSIZE 20
#define ElemType int
class Triple //三元组类
{
public:
int i, j; //行列号
ElemType e; //元素值
};
class TSMatrix //矩阵类
{
public:
Triple matrix[MAX_MATRIXSIZE]; //三元组集合
int mu, nu, tu; //行数,列数,非零元个数
};
class Matrix //矩阵类封装了有关矩阵的操作
{
public:
void MatrixMutiply(); //接口函数
private:
void GetMatrix(); //得到矩阵的三元组
void Mutiply(); //矩阵相乘
void PrintMatrix(TSMatrix&); //打印矩阵
void GetCpot(int[], TSMatrix&); //求得辅助数组Cpot的值//Cpot[i]代表行号为i的第一个元素在三元组中的位置
TSMatrix m, n, q; //实例化矩阵类的对象
};
void Matrix::MatrixMutiply() //接口函数
{
GetMatrix();
Mutiply();
PrintMatrix(m);
PrintMatrix(n);
PrintMatrix(q);
}
void Matrix::GetMatrix() //得到矩阵M,N的三元组
{
char name[2] =
{ 'M', 'N' };
TSMatrix *M[2] =
{ &m, &n };
for (int c = 0; c < 2; c++)
{
cout << "Please Input The Size Of The Matrix " << name[c] << "(m*n)"
<< endl;
cin >> M[c]->mu >> M[c]->nu;
M[c]->tu = 1;
cout << "Please Input Matrix With Increasing Order Of RowNumber" << endl
<< "rownum columnnum element" << endl << endl;
int i, j;
ElemType e;
while (cin >> i >> j >> e)
{
M[c]->matrix[M[c]->tu].i = i;
M[c]->matrix[M[c]->tu].j = j;
M[c]->matrix[M[c]->tu].e = e;
M[c]->tu++;
}
cin.clear();
}
}
void Matrix::GetCpot(int Cpot[], TSMatrix &t) //求得辅助数组Cpot的值//Cpot[i]代表行号为i的第一个元素在三元组中的位置
{
int num[MAX_MATRIXSIZE];
memset(num, 0, sizeof(num));
for (int i = 1; i < t.tu; i++)
num[t.matrix[i].i]++;
Cpot[1] = 1;
for (int i = 2; i <= t.mu + 1; i++)
Cpot[i] = Cpot[i - 1] + num[i - 1];
}
void Matrix::Mutiply()
{
int cpotm[MAX_MATRIXSIZE], cpotn[MAX_MATRIXSIZE];
GetCpot(cpotm, m);
GetCpot(cpotn, n);
int temp[MAX_MATRIXSIZE];
q.tu = 1;
for (int i = 1; i < m.tu; i = cpotm[m.matrix[i].i + 1])
{
memset(temp, 0, sizeof(temp));
for (int j = i; j < cpotm[m.matrix[i].i + 1]; j++)
{
for (int k = cpotn[m.matrix[j].j]; k < cpotn[m.matrix[j].j + 1];
k++)
temp[n.matrix[k].j] += m.matrix[j].e * n.matrix[k].e;
}
for (int j = 1; j <= n.nu; j++)
{
if (temp[j] != 0)
{
q.matrix[q.tu].i = m.matrix[i].i;
q.matrix[q.tu].j = j;
q.matrix[q.tu].e = temp[j];
q.tu++;
}
}
}
}
void Matrix::PrintMatrix(TSMatrix &t) //打印矩阵
{
for (int i = 1; i < t.tu; i++)
cout << t.matrix[i].i << " " << t.matrix[i].j << " " << t.matrix[i].e
<< endl;
cout << endl;
}
main.cpp
*代码丢失。。。待补充