矩阵的压缩存储
来源:互联网 发布:天界坐骑进化数据 编辑:程序博客网 时间:2024/05/20 00:36
对称矩阵A:N*N,A(i,j)=A(j,i)(0<=i<=N&&0<=j<=N)
压缩存储:只存储对称矩阵的上三角或下三角的数据,所以最多存储N*(N+1)/2个数据
对称矩阵和压缩存储的对应关系:SymmetricMatrix[i][j]=array[i*(i+1)/2+j]
#include<iostream>using namespace std;template<class T>class SymmetricMatrix{public:SymmetricMatrix(T* arr, int n):_row(n), _col(n), _data(new T[n*(n+1)/2]){int index = 0;for (int i = 0; i < n; ++i){for (int j = 0; j < n; ++j){if (i >= j){_data[index] = arr[i*n+j];index++;}}}}T getdata(int i, int j){if (i <= j){return _data[i*(i+1)/2 + j];}else{swap(i, j);return _data[i*(i + 1) / 2 + j];swap(j, i);}}void print(){for (int i = 0; i < _row; ++i){for (int j = 0; j < _col; ++j){cout << getdata(i, j) << " ";}cout << endl;}}private:int _row;int _col;T* _data;};int main(){int arr[5][5] = {{0,1,2,3,4},{1,0,1,2,3},{2,1,0,1,2},{3,2,1,0,1},{4,3,2,1,0}};SymmetricMatrix<int> array((int*)arr,5);array.print();system("pause");return 0;}
运行结果:
压缩存储:使用三元组{row,col,value}存储原矩阵中每一个有效值及其所在的行和列(以行优先级顺序依次存放)
#include<iostream>using namespace std;#include<vector>template<class T>struct trituple{trituple(size_t row, size_t col, T data) :_row(row) , _col(col) , _data(data){} trituple(){}size_t _row;size_t _col;T _data;};template<class T>class SpareseMatrix{public:SpareseMatrix(T* arr, size_t row, size_t col,T value):_row(row),_col(col),_value(value){for (size_t i = 0; i < row; ++i){for (size_t j = 0; j < col; ++j){if (arr[i*col + j] != _value){_v.push_back(trituple<T>(i, j, arr[i*col + j]));}}}}void print(){size_t index = 0;for (size_t i = 0; i < _row; ++i){for (size_t j = 0; j < _col; ++j){if (index != _v.size() && i==_v[index]._row && _v[index]._col == j){cout << _v[index]._data << " ";index++;}else{cout << _value << " ";}}cout << endl;}}private:vector<trituple<T>> _v;int _row;int _col;T _value;};int main(){int arr[6][5] = {{ 1,0,3,0,5},{ 0,0,0,0,0},{ 0,0,0,0,0},{ 1,0,3,0,5},{ 0,0,0,0,0},{ 0,1,4,0,0}};SpareseMatrix<int> array((int*)arr, 6, 5, 0);array.print();system("pause");return 0;}运行结果:
阅读全文
0 0
- 矩阵的压缩存储
- 矩阵的压缩存储
- 矩阵的压缩存储
- 矩阵的压缩存储
- 矩阵的压缩存储
- 矩阵的压缩存储
- 矩阵的压缩存储
- 矩阵的压缩存储
- 特殊矩阵的压缩存储
- 带状矩阵的压缩存储
- 稀疏矩阵的压缩存储
- 特殊矩阵的压缩存储
- 对称矩阵的压缩存储
- 稀疏矩阵的压缩存储
- 对称矩阵的压缩存储
- 稀疏矩阵的压缩存储
- 对称矩阵的压缩存储
- 稀疏矩阵的压缩存储
- HihoCoder
- 数据库查询表之间的连接分
- 方法之间参数传递获取不到原因
- glibc内存管理ptmalloc底层实现
- Spring Cloud 探索 | Mongodb 微服务
- 矩阵的压缩存储
- map
- 矩阵反转--计蒜客
- (哈哈)漫画告诉你什么是屎一样的代码(屎里蕴含着代码的秘密)
- golang-redis之list类型简单操作
- uboot详细分析
- StringBuffer类和包装类
- 开始我的程序员旅程
- 天耀18期