假设nn的稀疏矩阵A采用三元组表示,设计一个程序exp6-4.cpp实现如下功能:

(1)生成如下两个稀疏矩阵的三元组a和b;
       
(2)输出a转置矩阵的三元组;
(3)输出a+b的三元组;
(4)输出ab的三元组。
#include <iostream>
#include<cstdio>
using namespace std;
#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[1000];
} TSMatrix;
void CreatMat(TSMatrix &t,int 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++;
            }
        }
}
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 p,q=0,v;
    tb.rows=t.cols;
    tb.cols=t.rows;
    tb.nums=t.nums;
    if(t.nums!=0)
    {
        for(v=0; v<t.cols; v++)
            for(p=0; p<t.nums; p++)
            {
                tb.data[q].r=t.data[p].c;
                tb.data[q].c=t.data[p].r;
                tb.data[q].d=t.data[p].d;
                q++;
            }
    }
}
int main()
{
    TSMatrix t,t1,tb;
    int c[4][4];
    int a[M][N]= {{1,0,3,0},{0,1,0,0},{0,0,1,0},{0,0,1,1}};
    CreatMat(t,a);
    TranTat(t,tb);
    printf("a的三元组:\n");
    DispMat(t);
    printf("a的转置三元组:\n");
    DispMat(tb);
    int b[M][N]= {{3,0,0,0},{0,4,0,0},{0,0,1,0},{0,0,0,2}};
    CreatMat(t1,b);
    printf("b的三元组:\n");
    DispMat(t1);
    for (int i = 0; i < M; i++)
        for (int j = 0; j < N; j++)
            c[i][j] = a[i][j] + b[i][j];
    CreatMat(t,c);
    printf("a+b的和:\n");
    DispMat(t);
    int sum;
    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
        {
            sum = 0;
            for (int k = 0; k < N; k++)
            {
                sum += a[i][k] * b[k][j];
            }
            c[i][j]=sum;
        }
    }
    CreatMat(t,c);
    printf("a*b的三元组:\n");
    DispMat(t);
    return 0;
}

展开阅读全文

没有更多推荐了,返回首页