#include运行结果#include typedef int elem; typedef struct Triple{ int i; int j; elem e; }Triple,*TriplePtr; typedef struct CompressMatrix{ int rows,columns,numElements; Triple* elements; }CompressedMatrix,*CompressedMatrixPtr; CompressedMatrixPtr iniCompressedMatrix(int pRows,int pColumns,int pElements,int** pData){ int i; CompressedMatrixPtr result = (CompressedMatrixPtr)malloc(sizeof(CompressedMatrix)); result->rows = pRows; result->columns = pColumns; result->numElements = pElements; result->elements = (TriplePtr)malloc(pElements * sizeof(Triple)); for(i = 0;i < pElements;i++){ result->elements[i].i = pData[i][0]; result->elements[i].j = pData[i][1]; result->elements[i].e = pData[i][2]; } return result; } void printCompressedMatrix(CompressedMatrixPtr pPtr){ int i; for(i = 0;i < pPtr->numElements;i++){ printf("(%d,%d): %dn",pPtr->elements[i].i,pPtr->elements[i].j,pPtr->elements[i].e); } } CompressedMatrixPtr transposeCompressedMatrix(CompressedMatrixPtr pPtr){ int i,tempColumn,tempPosition; //记录同一列出现的次数 int *tempColumnCounts = (int*)malloc(pPtr->columns * sizeof(int)); //记录某一列转置后最早在哪行出现 int *tempOffsets = (int*)malloc(pPtr->columns * sizeof(int)); for(i = 0; i < pPtr->columns; i ++){ tempColumnCounts[i] = 0; } CompressedMatrixPtr resultPtr = (CompressedMatrixPtr)malloc(sizeof(CompressedMatrix)); resultPtr->rows = pPtr->columns; resultPtr->columns = pPtr->rows; resultPtr->numElements = pPtr->numElements; resultPtr->elements = (TriplePtr)malloc(pPtr->numElements * sizeof(struct Triple)); for(i = 0; i < pPtr->numElements; i ++) { tempColumnCounts[pPtr->elements[i].j] ++; } tempOffsets[0] = 0; for(i = 1; i < pPtr->columns; i ++){ tempOffsets[i] = tempOffsets[i - 1] + tempColumnCounts[i - 1]; printf("tempOffsets[%d] = %d rn", i, tempOffsets[i]); } for(i = 0; i < pPtr->numElements; i ++) { tempColumn = pPtr->elements[i].j; tempPosition = tempOffsets[tempColumn]; resultPtr->elements[tempPosition].i = pPtr->elements[i].j; resultPtr->elements[tempPosition].j = pPtr->elements[i].i; resultPtr->elements[tempPosition].e = pPtr->elements[i].e; tempOffsets[tempColumn]++; } return resultPtr; } void compressedMatrixTest(){ CompressedMatrixPtr tempPtr1, tempPtr2; int i, j, tempElements; tempElements = 4; int** tempMatrix1 = (int**)malloc(tempElements * sizeof(int*)); for(i = 0; i < tempElements; i ++){ tempMatrix1[i] = (int*)malloc(3 * sizeof(int)); } int tempMatrix2[4][3] = {{0, 0, 2}, {0, 2, 3}, {2, 0, 5}, {2, 1, 6}}; for(i = 0; i < tempElements; i ++){ for(j = 0; j < 3; j ++) { tempMatrix1[i][j] = tempMatrix2[i][j]; } } tempPtr1 = iniCompressedMatrix(2, 3, 4, tempMatrix1); printf("After initialization.rn"); printCompressedMatrix(tempPtr1); tempPtr2 = transposeCompressedMatrix(tempPtr1); printf("After transpose.rn"); printCompressedMatrix(tempPtr2); } int main(){ compressedMatrixTest(); return 0; }
After initialization. (0,0): 2 (0,2): 3 (2,0): 5 (2,1): 6 tempOffsets[1] = 2 tempOffsets[2] = 3 After transpose. (0,0): 2 (0,2): 5 (1,2): 6 (2,0): 3
PS:老师这算法真nb.



