5.18压缩矩阵的转置
#include stdio.h #include malloc.h typedef int elem; typedef struct Triple{ int i; int j; elem e; } Triple, *TriplePtr; /** * 压缩矩阵行数、列数、非零元个数、三元组数组 */ typedef struct CompressedMatrix{ int rows, cols, num; Triple* data; } CompressedMatrix, *CompressedMatrixPtr; /** * 初始化压缩矩阵 */ CompressedMatrixPtr initMatrix(int r, int c, int n, int** input){ int i; CompressedMatrixPtr p (CompressedMatrixPtr)malloc(sizeof(struct CompressedMatrix)); p-rows r; p-cols c; p-num n; p-data (TriplePtr)malloc(n * sizeof(struct Triple)); for(i 0; i n; i ){ p-data[i].i input[i][0]; p-data[i].j input[i][1]; p-data[i].e input[i][2]; } return p; } /** * 打印压缩矩阵 */ void printMatrix(CompressedMatrixPtr p){ int i; for(i 0; i p-num; i ){ printf((%d, %d): %d\r\n, p-data[i].i, p-data[i].j, p-data[i].e); } } /** * 矩阵转置 */ CompressedMatrixPtr transpose(CompressedMatrixPtr p){ int i, col, pos; int *counts (int*)malloc(p-cols * sizeof(int)); int *offsets (int*)malloc(p-cols * sizeof(int)); for(i 0; i p-cols; i ){ counts[i] 0; } CompressedMatrixPtr res (CompressedMatrixPtr)malloc(sizeof(struct CompressedMatrix)); res-rows p-cols; res-cols p-rows; res-num p-num; res-data (TriplePtr)malloc(p-num * sizeof(struct Triple)); // 第一步统计每列非零元个数 for(i 0; i p-num; i ) { counts[p-data[i].j] ; } // 第二步计算偏移量 offsets[0] 0; for(i 1; i p-cols; i ){ offsets[i] offsets[i - 1] counts[i - 1]; printf(offsets[%d] %d \r\n, i, offsets[i]); } // 第三步填充转置后的数据 for(i 0; i p-num; i ) { col p-data[i].j; pos offsets[col]; res-data[pos].i p-data[i].j; res-data[pos].j p-data[i].i; res-data[pos].e p-data[i].e; offsets[col]; } return res; } /** * 测试压缩矩阵 */ void testMatrix(){ CompressedMatrixPtr a, b; int i, j, n; n 4; int** input (int**)malloc(n * sizeof(int*)); for(i 0; i n; i ){ input[i] (int*)malloc(3 * sizeof(int)); } int raw[4][3] {{0, 0, 2}, {0, 2, 3}, {2, 0, 5}, {2, 1, 6}}; for(i 0; i n; i ){ for(j 0; j 3; j ) { input[i][j] raw[i][j]; } } a initMatrix(2, 3, 4, input); printf(初始化后:\r\n); printMatrix(a); b transpose(a); printf(转置后:\r\n); printMatrix(b); } /** * 主函数 */ int main(){ testMatrix(); return 1; }