稀疏矩阵 三元组顺序存储

#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;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值