#include <iostream>
#include<stdlib.h>
using namespace std;
struct cun //存放行、列、值
{
int hang,lie,value;
cun&operator = (cun&x)
{
hang = x.hang;
lie=x.lie;
value=x.value;
}
};
class juzhen //矩阵类
{
friend ostream& operator <<(ostream& output,juzhen& M);//运算符<<重载
friend istream& operator >>(istream& input,juzhen& M);//运算符>>重载
public:
juzhen(juzhen &x);//gouzao
juzhen(int maxSz=100); //定义大小
juzhen zhuanzhi(); //稀疏矩阵转置
juzhen Add(juzhen &b); //当前稀疏矩阵与b相加
private:
int rows,cols,terms;
cun *smArray;
int maxTerms;
};
ostream& operator << (ostream& output, juzhen& M)//运算符<<重载
{
for(int i=0; i<M.terms; i++)
if(M.smArray[i].value!=0)
output<<M.smArray[i].hang<<" "<<M.smArray[i].lie<<" "<<M.smArray[i].value<<endl;
return output;
};
istream& operator >>(istream& input,juzhen& M)//运算符>>重载
{
input>>M.rows>>M.cols>>M.terms;
for(int i=0; i<M.terms; i++)
{
input>>M.smArray[i].hang>>M.smArray[i].lie>>M.smArray[i].value;
}
return input;
}
juzhen::juzhen(juzhen &x)//构造函数1
{
rows=x.rows;
cols=x.cols;
terms=x.terms;
maxTerms=x.maxTerms;
smArray=new cun[maxTerms];
for(int i=0; i<terms; i++)
{
smArray[i]=x.smArray[i];
}
};
juzhen::juzhen(int maxSz):maxTerms(maxSz)//构造函数2
{
smArray=new cun[maxSz];
rows=cols=terms=0;
};
juzhen juzhen::zhuanzhi()
{
juzhen b(maxTerms);
b.rows=cols;
b.cols=rows;
b.terms=terms;
if(terms>0)
{
int j,i,currentB=0;
for(j=0; j<cols; ++j)
for(i=0; i<terms; ++i)
if(smArray[i].lie==j)
{
b.smArray[currentB].hang=j;
b.smArray[currentB].lie=smArray[i].hang;
b.smArray[currentB].value=smArray[i].value;
currentB++;
}
}
return b;
}
juzhen juzhen:: Add(juzhen &b)
{
juzhen result;//结果矩阵
int i=0,j=0,c,d;
result.terms=0;
while(i<terms&&j<b.terms)
{
c=cols*smArray[i].hang+smArray[i].lie;
d=cols*b.smArray[j].hang+b.smArray[j].lie;
if(c<d)
{
result.smArray[result.terms]=smArray[i];
i++;
}
else if(c>d)
{
result.smArray[result.terms]=b.smArray[j];
j++;
}
else
{
result.smArray[result.terms]=smArray[i];
result.smArray[result.terms].value=smArray[i].value+b.smArray[j].value;
i++;
j++;
}
result.terms++;
}
for(; i<terms; i++)
{
result.smArray[result.terms]=smArray[i];
result.terms++;
}
for(; j<b.terms; j++)
{
result.smArray[result.terms]= b.smArray[i];
result.terms++;
}
return result;
}
int main()
{
juzhen x,y,z,w;
cin>>x>>y;
z=x.zhuanzhi();
w=x.Add(y);
cout<<"The transformed matrix is:"<<endl;
cout<<z;
cout<<"The added matrix is:"<<endl ;
cout<<w;
return 0;
}