4.3.2 稀疏矩阵转置快速转置

Posted slowisfast

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了4.3.2 稀疏矩阵转置快速转置相关的知识,希望对你有一定的参考价值。

SparseMatrix.h

#pragma once
#include<iostream>
using namespace std;

class Tri {
public:
    int col;
    int row;
    int value;
};

class SparseMatrix {
public:
    int term;
    Tri* elements;
    int Srow;
    int Scol;

    SparseMatrix(int t = 2, int r = 10, int c = 10) {
        term = t;
        Srow = r;
        Scol = c;
        elements = new Tri[term];
    }

    void quickTranspose(SparseMatrix& B) {
        int* rowCount;
        int* rowBegin;
        rowCount = new int[Scol];
        rowBegin = new int[Scol];
        for (int i = 0; i < Scol; i++) {
            rowCount[i] = 0;
        }
        for (int i = 0; i < term; i++) {
            rowCount[elements[i].col]++;
        }
        
        for (int i = 0; i < Scol; i++) {
            rowBegin[i] = 0;
        }
        
        for (int i = 1; i < Scol; i++) {
            rowBegin[i] = rowBegin[i - 1] + rowCount[i - 1];
        }
        cout << "RowBegin:" << endl;
        for (int i = 1; i < Scol; i++) {
            cout << i << ":" << rowBegin[i] << "  ";
        }
        cout << endl;
        //完成辅助数组

        int index_B = 0;
        for (int i = 0; i < term; i++) {
            index_B = rowBegin[elements[i].col];
            B.elements[index_B].col = elements[i].row;
            B.elements[index_B].row = elements[i].col;
            B.elements[index_B].value = elements[i].value;
            rowBegin[elements[i].col]++;
        }
    }

    void show() {
        for (int i = 0; i < term; i++) {
            cout << elements[i].row << "," << elements[i].col << "," << elements[i].value << endl;
        }
    }

};

main.cpp

#include"SparseMatrix.h"

int main() {
    SparseMatrix A, B;
    A.elements[0].col = 9;
    A.elements[0].row = 0;
    A.elements[0].value = 8;
    A.elements[1].col = 0;
    A.elements[1].row = 6;
    A.elements[1].value = 6;
    A.show();
    cout << "----------------------" << endl;
    A.quickTranspose(B);
    B.show();
    return 0;
}

 

以上是关于4.3.2 稀疏矩阵转置快速转置的主要内容,如果未能解决你的问题,请参考以下文章

稀疏矩阵的压缩存储及快速转置

C++实现稀疏矩阵的压缩存储转置快速转置

用C试一下稀疏矩阵的快速转置

关于稀疏矩阵三元组的转置

数据结构----稀疏矩阵的快速转置

稀疏矩阵的列序递增法和一次定位快速转置法