您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验(矩阵的压缩存储)

2020-02-03 05:01 751 查看

数据结构实验(矩阵的压缩存储)

  • 实验目的:掌握数组这种抽象数据类型的特点;掌握稀疏矩阵的三元组表存储结构的描述方法和具体实现。

  • 实验要求:采用三元组顺序表存储方式,实现稀疏矩阵的快速转置算法。

  • 实验内容

#include<iostream.h>
//using namespace std;
#define OK 1
#define ERROR 0
typedef int Status;
typedef int ElemType;

//三元组顺序表类型定义
#define MAXSIZE 100
typedef struct
{
int i,j;
ElemType e;
}Triple;
typedef struct
{
Triple *data;//data[0]不用
int mu,nu,tu;
}TSMatrix;

//初始化三元组表
Status InitMatrix(TSMatrix &M)
{
M.data=new Triple[MAXSIZE+1];
M.mu=0;M.nu=0;M.tu=0;
return OK;
}

//按行优先顺序创建一个矩阵的三元组表
Status CreatMatrix(TSMatrix &M)
{
int t;
InitMatrix(M);
cout<<"*********欢迎进入转置系统*********\n\n";
cout<<"输入稀疏矩阵的行数、 列数和非零元素个数:"<<endl;
cin>>M.mu>>M.nu>>M.tu;
if(M.tu==0)return ERROR;
cout<<"按行序输入"<<M.tu<<"个非零元的三元组:"<<endl;
for(t=1;t<=M.tu;t++)
{
cout<<"输入第"<<t<<"个非零元的行号、列号和值:"<<endl;
cin>>M.data[t].i>>M.data[t].j>>M.data[t].e;
}
return OK;

}

//转置三元组表--快速转置法
Status FastTransMatrix(TSMatrix M,TSMatrix &T)
{//采用三元组顺序表存储表示,求稀疏矩阵M的转置矩阵T。
T.mu=M.nu; T.nu=M.mu; T.tu=M.tu;
int cpot[100];int num[100];
if(T.tu)
{
for(int col=1;col<=M.nu;++col)  num[col]=0;//num数组的初始化
for(int t=1;t<=M.tu;++t)  ++num[M.data[t].j];//求M中每一列含非零元个数
cpot[1]=1;
//求第col列中第一个非零元b.data中的序号
for(col=2;col<=M.nu;++col)  cpot[col]=cpot[col-1]+num[col-1];//求cpot向量
int q;
for(int p=1;p<=M.tu;++p){
col=M.data

.j; q=cpot[col]; T.data[q].i=M.data[p].j; T.data[q].j=M.data[p].i; T.data[q].e=M.data[p].e; ++cpot[col]; }//for }//if return OK; }//FastTransposeSMatrix //按三元组表方式输出一个矩阵 Status OutputMatrix(TSMatrix M) { int t; cout<<M.mu<<"行 "<<M.nu<<"列 "<<M.tu<<" 个非零元 "<<endl; cout<<" 各非零元分别为: "<<endl; for(t=1;t<=M.tu;t++) { cout<<M.data[t].i<<" "<<M.data[t].j<<" "<<M.data[t].e<<endl; } return OK; } //按阵列方式输出一个矩阵 Status PrintMatrix(TSMatrix M) { int row,col,k; int a[10][10]; for(row=1;row<=M.mu;row++) for(col=1;col<=M.nu;col++) a[row][col]=0; for(k=1;k<=M.tu; k++) { for(row=1;row<=M.mu;row++) for(col=1;col<=M.nu;col++) if((M.data[k].i==row)&&(M.data[k].j==col)) a[row][col]=M.data[k].e; } for(row=1;row<=M.mu;row++) { for(col=1;col<=M.nu;col++) cout<<a[row][col]<<" "; cout<<endl; } return OK; } int main() { TSMatrix M; TSMatrix T; CreatMatrix(M);//调用创建函数 cout<<endl<<"原始矩阵M为: "; OutputMatrix(M); cout<<endl; cout<<"原始矩阵M阵列为: "<<endl; PrintMatrix(M); InitMatrix(T); FastTransMatrix(M,T); cout<<endl<<"转置矩阵T为:"; OutputMatrix(T); cout<<endl; cout<<"转置矩阵T阵列为: "<<endl; PrintMatrix(T); return 0; }

  • [p]运行结果

  • 数据结构矩阵转置

to be continued
how
2019/11/19

  • 点赞
  • 收藏
  • 分享
  • 文章举报
qq_45297146 发布了5 篇原创文章 · 获赞 0 · 访问量 123 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: