三元组

假设nn的稀疏矩阵A采用三元组表示,设计一个程序exp6-4.cpp实现如下功能:
(1)生成如下两个稀疏矩阵的三元组a和b;
(2)输出a转置矩阵的三元组;
(3)输出a+b的三元组;
(4)输出ab的三元组。
#include 
#include 
#define MaxSize 16
#define M 4
#define N 4
typedef struct
{
    int r;
    int c;
    int d;
} TupNode;
typedef struct
{
    int rows;
    int cols;
    int nums;
    TupNode data[MaxSize];
} TSMatrix;
void CreatMat(TSMatrix *t,int A[][N])
{
    int i,j;
    t->cols=N;
    t->rows=M;
    t->nums=0;
    for(i=0; idata[t->nums].c=j;
                t->data[t->nums].r=i;
                t->data[t->nums].d=*(A[i]+j);
                t->nums++;
            }
        }

}
void OutputMat(TSMatrix *t)
{
    int i;
    printf("     %d    %d    %d\n",M,N,t->nums);
    printf("     -----------\n");
    for(i=0; inums; i++)
    {
        printf("     %d    %d    %d\n",t->data[i].r,t->data[i].c,t->data[i].d);
    }
}
void TranTat(TSMatrix *t,TSMatrix *a)
{
    t->cols=a->rows;
    t->rows=a->cols;
    t->nums=a->nums;
    int i,j,k=0;
    for(i=0; icols; i++)
        for(j=0; jnums; j++)
            if(i==a->data[j].c)
            {
                t->data[k].c=a->data[j].r;
                t->data[k].r=a->data[j].c;
                t->data[k].d=a->data[j].d;
                k++;
            }
}
void SumMat(int a[][N],int b[][N],int c[][N])
{
    int i,j;
    for (i = 0; i < M; i++)
        for (j = 0; j < N; j++)
            c[i][j] = a[i][j] + b[i][j];
}
void MultiMat(int a[][N],int b[][N],int c[][N])
{
    int i,j,k,sum;
    for (i = 0; i < M; i++)
    {
        for (j = 0; j < N; j++)
        {
            sum = 0;
            for (k = 0; k < N; k++)
            {
                sum += a[i][k] * b[k][j];
            }
            c[i][j]=sum;
        }
    }
}
int main()
{
    int A[M][N]= {{1,0,3,0},{0,1,0,0},{0,0,1,0},{0,0,1,1}},B[][N]= {{3,0,0,0},{0,4,0,0},{0,0,1,0},{0,0,0,2}},C[M][N];
    TSMatrix *a,*b,*c;
    a=(TSMatrix *)malloc(sizeof(TSMatrix));
    b=(TSMatrix *)malloc(sizeof(TSMatrix));
    c=(TSMatrix *)malloc(sizeof(TSMatrix));
    printf("a的三元组:\n");
    CreatMat(a,A);
    OutputMat(a);
    printf("b的三元组:\n");
    CreatMat(b,B);
    OutputMat(b);
    printf("a转置为c\n");
    printf("c的三元组:\n");
    TranTat(c,a);
    OutputMat(c);
    printf("c=a+b\n");
    printf("c的三元组:\n");
    SumMat(A,B,C);
    CreatMat(c,C);
    OutputMat(c);
    printf("c=a*b\n");
    printf("c的三元组:\n");
    MultiMat(A,B,C);
    CreatMat(c,C);
    OutputMat(c);
    return 0;
}

你可能感兴趣的:(三元组)