Chinaunix首页 | 论坛 | 博客
  • 博客访问: 156302
  • 博文数量: 36
  • 博客积分: 802
  • 博客等级: 准尉
  • 技术积分: 717
  • 用 户 组: 普通用户
  • 注册时间: 2012-06-02 22:47
文章分类
文章存档

2012年(36)

分类: C/C++

2012-08-28 18:14:13

稀疏矩阵三元组转置最常见,最容易理解的一个算法

点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<stdlib.h>

  3. #define MAXSIZE 100
  4. #define TRUE 1
  5. #define FALSE 0
  6. typedef struct
  7. {
  8.     int row,col;
  9.     int e;
  10. }Triple;
  11. typedef struct
  12. {
  13.     Triple data[MAXSIZE+1];
  14.     int m,n,len;
  15. }TSMatrix;

  16. TSMatrix *CreateMatrix()//构造稀疏矩阵
  17. {
  18.     TSMatrix *M=(TSMatrix *)malloc(sizeof(TSMatrix));
  19.     int m,n,num;
  20.     int i;
  21.     printf("请输入您想要的稀疏矩阵的行,列,非零元素个数。\n");
  22.     scanf("%d,%d,%d",&m,&n,&num);
  23.     
  24. //    M->data=(Triple *)malloc(sizeof(Triple)*num);
  25.     M->m=m;
  26.     M->n=n;
  27.     M->len=num;
  28.     i=0;
  29.     printf("开始矩阵构造!\n");
  30.     while(i<num)
  31.     {
  32.         scanf("%d %d %d",&M->data[i].row,&M->data[i].col,&M->data[i].e);
  33.         if(M->data[i].row>m||M->data[i].col>n)
  34.         {
  35.             printf("构造稀疏矩阵失败!\n");
  36.             exit(1);
  37.         }
  38.         i++;
  39.     }
  40.     return M;
  41. }
  42. void ShowMatrix(TSMatrix *M)
  43. {
  44.     int p;
  45.     printf("行数:%2d,列数:%2d,非0元素个数:%2d\n",M->m,M->n,M->len);
  46.     for(p=0;p<M->len;p++)
  47.         printf("%2d%2d%2d\n",M->data[p].row,M->data[p].col,M->data[p].e);
  48.     printf("\n");
  49. }
  50. //第一种转置方法
  51. void Change(TSMatrix *N)
  52. {
  53.     int i,j;
  54.     int k;
  55.     Triple *t=(Triple *)malloc(sizeof(Triple));
  56.     for(i=0;i<N->m;i++)
  57.     {
  58.         for(j=0;j<N->m-i;j++)
  59.             if(N->data[j].row>N->data[j+1].row)
  60.             {
  61.                 *t=N->data[j];
  62.                 N->data[j]=N->data[j+1];
  63.                 N->data[j+1]=*t;
  64.             }
  65.     }
  66. }

  67. TSMatrix * TransMatrix(TSMatrix *M)
  68. {
  69.     int q=0;
  70.     int col,p;
  71.     TSMatrix *N=(TSMatrix *)malloc(sizeof(TSMatrix));
  72. //    N->data=(Triple *)malloc(sizeof(Triple)*(M->len));
  73.     N->len=M->len;
  74.     N->m=M->n;
  75.     N->n=M->m;
  76.     for(col=0;col<M->n;col++)
  77.         for(p=0;p<M->len;p++)
  78.         {
  79.             if(M->data[p].row==col)
  80.             {
  81.                 N->data[q].row=M->data[p].col;
  82.                 N->data[q].col=M->data[p].row;
  83.                 N->data[q].e=M->data[p].e;
  84.                 q++;
  85.             }
  86.         }
  87.     Change(N);
  88.     return N;
  89. }

  90. int main()
  91. {
  92.     TSMatrix *M=CreateMatrix();
  93.     CreateMatrix(M);
  94.     ShowMatrix(M);
  95.     printf("转置以后的矩阵为:\n");
  96.     ShowMatrix(TransMatrix(M));
  97.     return 0;
  98. }

阅读(3413) | 评论(0) | 转发(2) |
给主人留下些什么吧!~~