稀疏矩阵使用三元组顺序表存储表示:
#include <iostream> using namespace std; #define MAXSIZE 12500 typedef struct { int i, j; int e; }Triple; typedef struct { Triple data[MAXSIZE + 1]; int rpos[MAXSIZE + 1]; int mu, nu, tu; }TSMatrix; int FastTransposeSMatrix(TSMatrix M, TSMatrix &T); int main() { TSMatrix M, T; int k; cout<< "输入矩阵行数m、列数n、元素个数n:"<<endl; cin >> M.mu >> M.nu >> M.tu; cout<<"请输入矩阵M(i,j,key):"<<endl; for (k = 1; k <= M.tu; ++k) cin>>M.data[k].i>>M.data[k].j>>M.data[k].e; FastTransposeSMatrix(M, T); cout<<"转置矩阵T为:"<<endl; for (k = 1; k <= T.tu; ++k) cout<<T.data[k].i<<" "<<T.data[k].j<<" "<<T.data[k].e<<endl; return 0; } int FastTransposeSMatrix(TSMatrix M, TSMatrix &T) { int col, t, p, q, *num, *cpot; T.mu = M.nu; T.nu = M.mu; T.tu = M.tu; if (T.tu) { num = new int[M.nu + 1]; cpot = new int[M.nu + 1]; for ( col = 1; col <= M.nu; ++col) num[col] = 0; for ( t = 1; t <= M.tu; ++t) ++num[M.data[t].j]; cpot[1] = 1; for (col = 2; col <= M.nu; ++col) cpot[col] = cpot[col - 1] + num[col - 1]; for (p = 1; p <= M.tu; ++p) { col = M.data[p].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]; } } return 0; }