第九周项目3-稀疏矩阵的三元组表示的实现及应用(1)
来源:互联网 发布:国行a1533支持什么网络 编辑:程序博客网 时间:2024/06/02 01:59
tup.h:
- #include <stdio.h>
- #define MaxSize 100
- #define M 6
- #define N 7
- typedef int ElemType;
- typedef struct
- {
- int r;
- int c;
- ElemType d;
- } TupNode;
- typedef struct
- {
- int rows;
- int cols;
- int nums;
- TupNode data[MaxSize];
- } TSMatrix;
- void CreatMat(TSMatrix &t,ElemType A[M][N]);
- bool Assign(TSMatrix t,ElemType &x,int i,int j);
- bool Value(TSMatrix &t,ElemType x,int i,int j);
- void DispMat(TSMatrix t);
- void TranTat(TSMatrix t,TSMatrix &tb);
tup.cpp:
- #include "tup.h"
- void CreatMat(TSMatrix &t,ElemType A[M][N])
- {
- int i,j;
- t.rows=M,t.cols=N,t.nums=0;
- for(i=0;i<M;i++)
- {
- for(j=0;j<N;j++)
- {
- if(A[i][j]!=0)
- {
- t.data[t.nums].r=i;
- t.data[t.nums].c=j;
- t.data[t.nums].d=A[i][j];
- t.nums++;
- }
- }
- }
- }
- bool Assign(TSMatrix t,ElemType &x,int i,int j)
- {
- int k=0;
- if(i>=t.rows || j>=t.cols)
- return false;
- while(k<t.nums && i>t.data[k].r)
- k++;
- while(k<t.nums && i==t.data[k].r && j>t.data[k].c)
- k++;
- if(t.data[k].r==i && t.data[k].c==j)
- x=t.data[k].d;
- else
- x=0;
- return true;
- }
- bool Value(TSMatrix &t,ElemType x,int i,int j)
- {
- int k=0;
- int k1;
- if(i>=t.rows || j>=t.cols)
- return false;
- while(k<t.nums && i>t.data[k].r)
- k++;
- while(k<t.nums && i==t.data[k].r && j>t.data[k].c)
- k++;
- if(t.data[k].r==i && t.data[k].c==j)
- t.data[k].d=x;
- else
- {
- for(k1=t.nums-1;k1>=k;k1--)
- {
- t.data[k1+1].r=t.data[k1].r;
- t.data[k1+1].c=t.data[k1].c;
- t.data[k1+1].d=t.data[k1].d;
- }
- t.data[k].r=i;
- t.data[k].c=j;
- t.data[k].d=x;
- t.nums++;
- }
- return true;
- }
- void DispMat(TSMatrix t)
- {
- int i;
- if(t.nums<=0)
- return;
- printf("\t%d\t%d\t%d\n",t.rows,t.cols,t.nums);
- printf("\t------------------\n");
- for(i=0;i<t.nums;i++)
- printf("\t%d\t%d\t%d\n",t.data[i].r,t.data[i].c,t.data[i].d);
- }
- void TranTat(TSMatrix t,TSMatrix &tb)
- {
- int i,j;
- int k=0;
- tb.rows=t.cols,tb.cols=t.rows,tb.nums=t.nums;
- if(t.nums!=0)
- {
- for(i=0;i<t.cols;i++)
- {
- for(j=0;j<t.nums;j++)
- {
- if(t.data[j].c==i)
- {
- tb.data[k].r=t.data[j].c;
- tb.data[k].c=t.data[j].r;
- tb.data[k].d=t.data[j].d;
- k++;
- }
- }
- }
- }
- }
main.cpp:
- #include <stdio.h>
- #include "tup.h"
- int main()
- {
- TSMatrix t,tb;
- int x,y=10;
- int A[6][7]=
- {
- {0,0,1,0,0,0,0},
- {0,2,0,0,0,0,0},
- {3,0,0,0,0,0,0},
- {0,0,0,5,0,0,0},
- {0,0,0,0,6,0,0},
- {0,0,0,0,0,7,4}
- };
- CreatMat(t,A);
- printf("b:\n");
- DispMat(t);
- if (Assign(t,x,2,5)==true)
- printf("Assign(t,x,2,5)=>x=%d\n",x);
- else
- printf("Assign(t,x,2,5)=>参数错误\n");
- Value(t,y,2,5);
- printf("执行Value(t,10,2,5)\n");
- if (Assign(t,x,2,5)==true)
- printf("Assign(t,x,2,5)=>x=%d\n",x);
- else
- printf("Assign(t,x,2,5)=>参数错误\n");
- printf("b:\n");
- DispMat(t);
- TranTat(t,tb);
- printf("矩阵转置tb:\n");
- DispMat(tb);
- return 0;
- }
运行结果:
0 0