标签:
#include <cstdio> #include <cstdlib> //#define _OJ_ typedef struct Triple1 { int i1; int j1; int data; //用三元组表来存储稀疏矩阵 } Triple1, *Triple; typedef struct Matrix1 { Triple1 elem[100]; int row; int colum; int cnt; //压缩矩阵行数列数及非零数的个数 } Matrix1, *Matrix; void TansposeMatrix(Matrix M, Matrix T) { int i, j, q; T->cnt = M->cnt; T->row = M->colum; T->colum = M->row; if(M->cnt > 0) { q = 1; for(i = 1;i <= T->row; i++) { //0号位不用T中的行从小到大去寻找M中的列配对 for(j = 1;j <= T->cnt; j++) { //和elem中的数每一个j1配对 if(i == M->elem[j].j1) { T->elem[q].i1 = M->elem[j].j1; T->elem[q].data = M->elem[j].data; T->elem[q].j1 = M->elem[j].i1; q++; } } } } } // 当非零个数和row * colum 相同时候 复杂度为row * colum * colum;仅仅适于cnt<<row * colum时 void transposematrix1(Matrix M, Matrix T) { int i, j, col, p; int num[100], cpot[100]; T->row = M->colum; T->colum = M->row; T->cnt = M->cnt; if(T->cnt > 0) { for(i = 1;i <= M->colum; i++) num[i] = 0; for(i = 1;i <= M->cnt; i++) ++num[M->elem[i].j1]; //计算M中每一列的非零元素个数 cpot[0] = 1; for(j = 1;j <= M->colum; j++) cpot[j] = cpot[j - 1] + num[j - 1]; //计算每一列的第一个非零元素在elem的下标 for(i = 1;i <= M->cnt; i++) { col = M->elem[i].j1; p = cpot[col]; T->elem[p].i1 = M->elem[i].j1; T->elem[p].j1 = M->elem[i].i1; T->elem[p].data = M->elem[i].data; ++cpot[col]; //计算完第一个后下标加一以便第n个非零元素计算 } } } //复杂度为cnt + colum 当cnt = row * colum 和经典算法一样为row * colum; int main(int argc, char const *argv[]) { #ifndef _OJ_ //ONLINE_JUDGE freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int i; Matrix M, T; M = (Matrix) malloc (sizeof(Matrix1)); T = (Matrix) malloc (sizeof(Matrix1)); scanf("%d %d %d", &M->row, &M->colum, &M->cnt); printf("原矩阵如下:\n"); for(i = 1;i <= M->cnt; i++) { scanf("%d %d %d", &M->elem[i].i1, &M->elem[i].j1, &M->elem[i].data); printf("%d %d %d\n", M->elem[i].i1, M->elem[i].j1, M->elem[i].data); } TansposeMatrix(M, T); printf("稀疏矩阵的转置算法一如下所示:\n"); for(i = 1;i <= T->cnt; i++) printf("%d %d %d\n", T->elem[i].i1, T->elem[i].j1, T->elem[i].data); transposematrix1(M, T); printf("稀疏矩阵的转置算法二如下所示:\n"); for(i = 1;i <= T->cnt; i++) printf("%d %d %d\n", T->elem[i].i1, T->elem[i].j1, T->elem[i].data); return 0; }
标签:
原文地址:http://www.cnblogs.com/airfand/p/5021679.html