美文网首页
数据结构稀疏矩阵的快速转置算法实现

数据结构稀疏矩阵的快速转置算法实现

作者: 学习微站 | 来源:发表于2022-11-16 14:03 被阅读0次
    #include <stdio.h> #include <stdlib.h> #include <process.h> #define MAXSIZE 200 typedef struct triple { int i; int j; int e; }Triple; typedef struct tabletype { int mu; int nu; int tu; Triple data[MAXSIZE]; }Tabletype; void CreatSMatrix(Tabletype *); void DestroySMatrix(Tabletype *); void out_matrix(Tabletype *); int FastTransposeSMatrix(Tabletype *, Tabletype *); int main(void) { char ch; Tabletype a = { 0,0,0,{0,0,0} }; Tabletype b; while (1) { printf("本程序的功能是实现稀疏矩阵的快速转置:\n"); CreatSMatrix(&a); printf("源矩阵:\n"); out_matrix(&a); if (FastTransposeSMatrix(&a, &b)) { printf("在转置矩阵之后: \n"); out_matrix(&b); } else { printf("矩阵为零:\n"); out_matrix(&a); } printf("Input 'q' to quit and 'c' run again:"); do { if ((ch = getchar()) == 'q' || ch == 'Q') { DestroySMatrix(&a); DestroySMatrix(&b); exit(0); } } while ((ch != 'C') && (ch != 'c')); system("cls"); } return 1; } void CreatSMatrix(Tabletype *a) { int i; printf("请输入矩阵的行数、列数和非零元个数,用空格间隔:"); scanf("%d%d%d", &(a->mu), &(a->nu), &(a->tu)); for (i = 1; i <= a->tu;) { printf("请输入矩阵中第%d个非零元(按行标、列标、值的顺序,空格间隔):", i); scanf("%d%d%d", &(a->data[i].i), &(a->data[i].j), &(a->data[i].e)); if (a->data[i].i < 1 || a->data[i].i > a->mu || a->data[i].j < 1 || a->data[i].j > a->nu) { printf("注意:下标越界输入数据无效!\n请重新输入:行标范围:1--%d,列标范围1--%d!!!\n", a->mu, a->nu); continue; } if (((a->data[i].i) < (a->data[i - 1].i)) || (((a->data[i].i) == (a->data[i - 1].i)) && ((a->data[i].j) <= (a->data[i - 1].j)))) { printf("注意:输入数据无效!\n请按照按行存储的顺序输入数据!\n"); continue; } i++; } } void DestroySMatrix(Tabletype *a) { (*a).mu = 0; (*a).nu = 0; (*a).tu = 0; } void out_matrix(Tabletype *a) { int i, j, k = 1; for (i = 1; i <= a->mu; i++) { for (j = 1; j <= a->nu; j++) { if ((a->data[k].i == i) && (a->data[k].j == j)) { printf("%4d", a->data[k].e); k++; } else printf("%4d", 0); } printf("\n"); } } int FastTransposeSMatrix(Tabletype *a, Tabletype *b) { int p, q, col; int *num; int *cpot; b->mu = a->nu; b->nu = a->mu; b->tu = a->tu; num = (int *)malloc((b->nu + 1) * sizeof(int)); cpot = (int *)malloc((b->nu + 1) * sizeof(int)); if (b->tu) { for (col = 0; col < a->nu; col++) num[col] = 0; for (col = 0; col <= a->tu; col++) num[a->data[col].j]++; cpot[1] = 1; for (col = 2; col <= a->nu; col++) cpot[col] = num[col - 1] + cpot[col - 1]; for (p = 1; p <= a->tu; p++) { col = a->data[p].j; q = cpot[col]; b->data[q].i = a->data[p].j; b->data[q].j = a->data[p].i; b->data[q].e = a->data[p].e; q++; cpot[col]++; } free(num); free(cpot); return 1; } else return 0; }

    本文使用 文章同步助手 同步

    相关文章

      网友评论

          本文标题:数据结构稀疏矩阵的快速转置算法实现

          本文链接:https://www.haomeiwen.com/subject/lqgqtdtx.html