#include <iostream>
using namespace std;
#define MaxSize 10
typedef int elemtype;
struct Tripe
{
int row,col;
elemtype val;
};
struct Seq_S_Matrix
{
int m,n,t;
Tripe sm[MaxSize+1];
};
void InitMatrix(Seq_S_Matrix &M)
{
M.n=M.m=M.t=0;
}
void Input(Seq_S_Matrix &M,int m, int n)
{
int t,i,j;
elemtype x;
t=0;
M.m=m;
M.n=n;
do
{
t++;
cin>>i>>j>>x;
M.sm[t].row=i;
M.sm[t].col=j;
M.sm[t].val=x;
}while((i!=0)&&(j!=0));
M.t=t-1;
}
int Output(Seq_S_Matrix M) /*输出稀疏矩阵方法一*/
{
int t,i,j;
t=1;
if(M.t==0)
{
cout<<"该矩阵没有非0元素"<<endl;
return 0;
}
for(i=1;i<=M.m;i++)
{ for(j=1;j<=M.n;j++)
{
if((M.sm[t].row==i)&&(M.sm[t].col==j))
{
cout<<M.sm[t].val<<" ";
t++;
}
else cout<<"0 ";
}
cout<<endl;
}
if(M.t==t-1)
{
cout<<"该矩阵输出完成"<<endl;
return 1;
}
else
{
cout<<"该矩阵元素没有完成输出"<<endl;
return 0;
}
}
int Output2(Seq_S_Matrix M) /*输出稀疏矩阵方法2*/
{
int i;
if(M.t==0)
{
cout<<"该矩阵没有非0元素"<<endl;
return 0;
}
cout<<"该稀疏矩阵由"<<M.m<<"行"<<M.n<<"列,共有元素"<<M.t<<"个"<<endl;
for(i=1;i<=M.t;i++)
{
cout<<M.sm[i].row<<" "<<M.sm[i].col<<" "<<M.sm[i].val<<endl;
}
cout<<"该矩阵输出完成"<<endl;
return 1;
}
void Transpose(Seq_S_Matrix A,Seq_S_Matrix &B) /* 转置方法一,复杂度(n*t) */
{
int i,j,t;
t=1;
InitMatrix(B);
for(j=1;j<=A.n;j++) /* 每次对全体数据扫描找出每列的非0元素置入B中 */
for(i=1;i<=A.t;i++)
{
if(A.sm[t].col==j)
{
B.sm[t].row=A.sm[t].col;
B.sm[t].col=A.sm[t].row;
B.sm[t].val=A.sm[t].val;
t++;
}
}
}
void Transpose2(Seq_S_Matrix A,Seq_S_Matrix &B) /* 转置访法2 */
{
InitMatrix(B);
int m,n,t,k;
int i,j;
m=A.m;
n=A.n;
t=A.t;
int *num=new int[n+1]; /* 记录每列非0元素个数 */
int *pos=new int[n+1]; /* 记录每列第1个非0元素的位置 */
for(j=1;j<=n;j++)
{
num[j]=0;
pos[j]=0;
}
for(i=1;i<=A.t;i++)
{
num[A.sm[i].col]++;
}
pos[1]=1;
for(j=2;j<=A.n;j++)
{
pos[j]=pos[j-1]+num[j-1]; /* 当前列的第1个非0元素的位置是前列第1个元素的位置加上前列非0元素的个数 */
}
for(i=1;i<=A.t;i++)
{
row=A.sm[i].row;
col=A.sm[i].col;
k=pos[col];
B.sm[k].col=row;
B.sm[k].row=col;
B.sm[k].val=A.sm[i].val;
pos[col]++;
}
delete []num;
delete []pos;
}