稀疏矩阵转置
本文采用顺序存储结构的三元组表压缩存储稀疏矩阵,并基于此数据结构对稀疏矩阵进行转置,介绍两种转置处理方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| #include<iostream> using namespace std;
#define MAXSIZE 500
typedef int ElemType; typedef bool Status;
typedef struct { int i, j; ElemType value; }Triple;
typedef struct { Triple data[MAXSIZE + 1]; int rows, cols, nums; }TSMatrix;
Status TransposeMatrix(TSMatrix M, TSMatrix& T); Status FastTransposeMatrix(TSMatrix M, TSMatrix& FT); Status TSMatrixRead(TSMatrix& M); Status TSMatrixPrint(TSMatrix M); int main() { TSMatrix M, T, FT; TSMatrixRead(M); cout << "Before Transpose Matrix:\n"; TSMatrixPrint(M); cout << "After Transpose Matrix:\n"; TransposeMatrix(M, T); TSMatrixPrint(T); cout << "After FastTranspose Matrix:\n"; FastTransposeMatrix(M, FT); TSMatrixPrint(FT); return 0; }
Status TransposeMatrix(TSMatrix M, TSMatrix& T) { T.rows = M.cols; T.cols = M.rows; T.nums = M.nums; if (T.nums) { int q = 1; for (int col = 1; col <= M.cols; col++) { for (int p = 1; p <= M.nums; p++) { if (M.data[p].j == col) { T.data[q].i = M.data[p].j; T.data[q].j = M.data[p].i; T.data[q].value = M.data[p].value; q++; } } } } return true; } Status FastTransposeMatrix(TSMatrix M, TSMatrix& FT) { FT.rows = M.cols; FT.cols = M.rows; FT.nums = M.nums; if (FT.nums) { int* num = new int[M.cols + 1]; int* cpot = new int[M.cols + 1]; for (int col = 1; col <= M.cols; col++) num[col] = 0; for (int t = 1; t <= M.nums; ++t) ++num[M.data[t].j]; cpot[1] = 1; for (int col = 2; col <= M.cols; col++) cpot[col] = cpot[col - 1] + num[col - 1]; for (int p = 1; p <= M.nums; p++) { int col = M.data[p].j; int q = cpot[col]; FT.data[q].i = M.data[p].j; FT.data[q].j = M.data[p].i; FT.data[q].value = M.data[p].value; cpot[col]++; } delete[] num; } return true; } Status TSMatrixRead(TSMatrix& M) { cout << "Input Matrix rows, cols and nums:\n"; cin >> M.rows >> M.cols >> M.nums; cout << "Input Matrix elements:\n"; for (int i = 1; i <= M.nums; i++) { cin >> M.data[i].i >> M.data[i].j >> M.data[i].value; } return true; } Status TSMatrixPrint(TSMatrix M) { int cnt = 1; for (int i = 1; i <= M.rows; i++) { for (int j = 1; j <= M.cols; j++) { if (M.data[cnt].i == i && M.data[cnt].j == j) cout << M.data[cnt++].value << " "; else cout << "0 "; } cout << endl; } return true; }
|
这里给出一个演示算例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
|