问题
描述
- 数据压缩是提高传输、存储效率一种技术。教材第5章介绍了两种简单的压缩存储方法。本实验要求实现三元组顺序表表示下的矩阵快速转置算法。
输入
- 稀疏矩阵的行数、列数、非零元个数(三个数都大于0)
以行为主序输入稀疏矩阵三元组表
输出
- 辅助数组num[ ]
辅助数组cpot[ ]
以行为主序输出对应的转置矩阵三元组表
测试用例
-
测试输入
-
6 7 8
1 2 12
1 3 9
3 1 -3
3 6 14
4 3 24
5 2 18
6 1 15
6 4 -7 -
期待输出
-
num:2,2,2,1,0,1,0,
cpot:1,3,5,7,8,8,9,
1,3,-3
1,6,15
2,1,12
2,5,18
3,1,9
3,4,24
4,6,-7
6,3,14
解题
分析
- num存的是原矩阵中第j列的元素个数
- cpot存的是原矩阵中对应列下一个元素的在三元组中的位置,使用后会改变
代码
#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
// 三元组节点
typedef struct node{
int i;
int j;
int data;
}NODE;
int main(){
// 行、列、非零元个数
int row,clum,counts;
// 用来遍历
int i;
int index;
//freopen("file in.txt","r",stdin);
cin>>row>>clum>>counts;
// 判断是否符合
if(row<=0||clum<=0||counts<=0){
return 0;
}
// 声明动态结构数组
NODE list[counts],newlist[counts];
for(i=0;i<counts;i++){
cin>>list[i].i>>list[i].j>>list[i].data;
}
// 不能在声明结构数组的同时进行初始化,这样会报错,可以在声明完成后初始化
// int num[clum]={0},cpot[clum];
int num[clum],cpot[clum];
for(i=0;i<clum;i++){
num[i]=0;
}
// 扫描到以后相应增加
for(i=0;i<counts;i++){
num[(list[i].j)-1]++;
}
// 根据num生成cpot
cpot[0]=1;
for(i=1;i<clum;i++){
cpot[i]=cpot[i-1]+num[i-1];
}
// 先输出,不然后面程序操作会改变cpot的值
cout<<"num:";
for(i=0;i<clum;i++){
cout<<num[i]<<",";
}
cout<<endl;
cout<<"cpot:";
for(i=0;i<clum;i++){
cout<<cpot[i]<<",";
}
cout<<endl;
// 特别注意下标的规律
for(i=0;i<counts;i++){
index=cpot[(list[i].j)-1]-1;
cpot[(list[i].j)-1]++;
newlist[index].data = list[i].data;
newlist[index].i = list[i].j;
newlist[index].j = list[i].i;
}
for(i=0;i<counts;i++){
cout<<newlist[i].i<<",";
cout<<newlist[i].j<<",";
cout<<newlist[i].data<<endl;
}
return 0;
}
小结
- 理解三元组存储矩阵和快速转置原理是重点
- 动态数组不能在声明的同时进行初始化,初始化需要在声明完成之后