#include<iostream>
using namespace std;
const int Max=100;
const int Max_rows=4;
const int Max_cols=7;
typedef class
{
public :
int r;
int c;
int e;
}TupNode;
typedef class
{
public :
int rows;
int cols;
int nums;
TupNode date[Max];
}TSMatrix;
void display(TSMatrix &m); //输出压缩后的稀疏矩阵
void show(TSMatrix &m);//输出完整的稀疏矩阵
void init_matrix(TSMatrix &m,int r,int c,int a[][Max_cols]);//矩阵的初始化
void add(TSMatrix m1,TSMatrix m2,TSMatrix &m3);
int main()
{
int a1[Max_rows][Max_cols]=
{
{0,8,0,6,0,2,0},
{0,0,34,54,0,0,2},
{-7,0,0,0,0,0,0},
{0,0,0,0,-12,0,0}
};
TSMatrix t1,t2,t3;
init_matrix(t1,Max_rows,Max_cols,a1);
show(t1);
display(t1);
cout<<endl;
int a2[Max_rows][Max_cols]=
{
{0,0,24,2,0,2,0 },
{0,8,0,7,14,2,0 },
{0,0,0,0,0,2,0 },
{0,-13,0,6,0,2,0},
};
init_matrix(t2,Max_rows,Max_cols,a2);
show(t2);
display(t2);
add(t1,t2,t3);
show(t3);
display(t3);
return 0;
}
void show(TSMatrix &m)//输出完整的稀疏矩阵
{
int i,j,k=0;
for(i=0;i<m.rows;i++)
{
for(j=0;j<m.cols;j++)
{
if(m.date[k].r==i&&m.date[k].c==j)
{
cout<<m.date[k].e<<" ";
k++;
}
else
{
cout<<0<<" ";
}
}
cout<<endl;
}
cout<<endl;
}
void display(TSMatrix &m) //输出压缩后的稀疏矩阵
{
int i;
for(i=0;i<m.nums;i++)
{
cout<<m.date[i].e<<" ";
}
cout<<endl;
}
void init_matrix(TSMatrix &m,int r,int c,int a[][Max_cols])//矩阵的初始化
{
int i,j,counts=0;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
if(a[i][j]!=0)
{
m.date[counts].r=i;
m.date[counts].c=j;
m.date[counts].e=a[i][j];
counts++;
}
}
}
m.nums=counts;
m.rows=r;
m.cols=c;
}
void add(TSMatrix m1,TSMatrix m2,TSMatrix &m3)
{
int i=0,j=0,nums=0;
while(i<m1.nums&&j<m2.nums)
{
if(m1.date[i].r==m2.date[j].r)
{
if(m1.date[i].c<m2.date[j].c)
{
m3.date[nums].c=m1.date[i].c;
m3.date[nums].r=m1.date[i].r;
m3.date[nums].e=m1.date[i].e;
nums++;
i++;
}
else if(m1.date[i].c>m2.date[j].c)
{
m3.date[nums].c=m2.date[j].c;
m3.date[nums].r=m2.date[j].r;
m3.date[nums].e=m2.date[j].e;
j++;
nums++;
}
else
{
if(m1.date[i].e+m2.date[j].e!=0)
{
m3.date[nums].c=m1.date[i].c;
m3.date[nums].r=m1.date[i].r;
m3.date[nums].e=m1.date[i].e+m2.date[j].e;
nums++;
i++;
j++;
}
}
}
else if(m1.date[i].r<m2.date[j].r)
{
m3.date[nums].r=m1.date[i].r;
m3.date[nums].c=m1.date[i].c;
m3.date[nums].e=m1.date[i].e;
nums++;
i++;
}
else
{
m3.date[nums].r=m2.date[j].r;
m3.date[nums].c=m2.date[j].c;
m3.date[nums].e=m2.date[j].e;
j++;
nums++;
}
if(i==m1.nums)
{
if(j<m2.nums)
{
while(j<m2.nums)
{
m3.date[nums].r=m2.date[j].r;
m3.date[nums].c=m2.date[j].c;
m3.date[nums].e=m2.date[j].e;
nums++;
j++;
}
break;
}
}
else if(j==m2.nums)
{
if(i<m1.nums)
{
while(i<m1.nums)
{
m3.date[i].r=m1.date[i].r;
m3.date[i].c=m1.date[i].c;
m3.date[i].e=m1.date[i].e;
i++;
nums++;
}
break;
}
}
else if(i==m1.nums&&j==m2.nums)
{
break;
}
}
m3.rows=m1.rows;
m3.cols=m1.cols;
m3.nums=nums;
}
————————————————
版权声明:本文为优快云博主「van之风」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/weixin_44077170/article/details/101480025