稀疏矩阵转置矩阵

num[]:矩阵A中某列的非零元素的个数
cpot[]:初值表示矩阵A中某列第一个非零元素在B中的位置,并有如下递推

{ c p o t [ 1 ] = 0 ; c p o t [ c o l ] = c p o t [ c o l − 1 ] + n u m [ c o l − 1 ] ; 2 < = c o l < = n u \left\{ \begin{array}{c} cpot[1]=0; \\ cpot[col]=cpot[col-1]+num[col-1]; 2<=col<=nu \end{array}\right. {cpot[1]=0;cpot[col]=cpot[col1]+num[col1];2<=col<=nu
 

代码

#include <iostream>

using namespace std;
/******************************************
对应教材4.5.1节,稀疏矩阵的转置算法 2
*******************************************/
using namespace std;

struct element
{
    int row, col;
    int item;
};

const int MaxTerm = 100;

struct SparseMatrix
{
    element data[MaxTerm];
    int mu, nu, tu; //行数、列数、非零元个数
};

void Trans2(SparseMatrix &A, SparseMatrix &B);
void Print(SparseMatrix A);

int main()
{
    SparseMatrix A = {{{1, 1, 3},{1, 4, 7},{2, 3, -1},{3, 1, 2},{5, 4, -8}},5, 4, 5};
    SparseMatrix B;
    Trans2(A, B);
    Print(B);
    return 0;
}

void Trans2(SparseMatrix &A, SparseMatrix &B)
{
    int i, j, k, num[MaxTerm] = {0}, cpot[MaxTerm] = {0};
        B.mu = A.nu; B.nu = A.mu; B.tu = A.tu;
    for (i = 0; i < A.tu; i++)
    {
        j = A.data[i].col;
        num[j]++;
    }
    cpot[1] = 0;
    for (i = 2; i <= A.nu; i++)
        cpot[i] = cpot[i - 1] + num[i - 1];

     cout<<"num";
    for(int i=0;i<A.tu;i++){
        cout<<num[i]<<" ";
    }
    cout<<endl;
    cout<<"cpot"<<endl;
    for(int i=0;i<A.tu;i++)
        cout<<cpot[i]<<" ";
    cout<<endl;


    for (i = 0; i < A.tu; i++)
    {
        j = A.data[i].col;
        k = cpot[j];
        B.data[k].row = A.data[i].col;
        B.data[k].col = A.data[i].row;
        B.data[k].item = A.data[i].item;
        cpot[j]++;
    }
}


void Print(SparseMatrix A)
{
    for (int i = 0; i < A.tu; i++)
    {
        cout << "(" << A.data[i].row << "," << A.data[i].col << ")" << A.data[i].item << endl;
    }
}

 

题解

根据上面代码的例子进行解释:

num为0,2,0,1,2
cpot为0,0,2,2,3
num的存在只是为了计算出cpot,这是累加法,每次计算完后cpot[j]++是因为如果第一列有两个非零数,第一个数字已经占了B矩阵的第一个,那么第二个数字只能占B矩阵的第二个。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值