Fast matrix transposition algorithm

Fast matrix transposition algorithm

Topic information

Data compression is a technique to improve transmission and storage efficiency. This experiment requires the realization of a fast matrix transposition algorithm under the representation of the triple sequence table.

enter

The number of rows, columns, and number of non-zero elements of the sparse matrix (all three numbers are greater than 0)
are entered into the sparse matrix triplet table in the main sequence of rows

Output

The auxiliary array num[]
auxiliary array cpot[]
outputs the corresponding transposed matrix triplet table in the main sequence of rows

answer

#include <iostream>

using namespace std;

struct Node
{
    
    
    int x;
    int y;
    int data;
};

int main()
{
    
    
    //freopen("/Users/zhj/Downloads/test.txt", "r", stdin);
    int N, M, NUM;
    cin >> N >> M >> NUM;

    Node Matrix[NUM];//原矩阵
    for (int i = 0; i < NUM; i++)
    {
    
    
        cin >> Matrix[i].x >> Matrix[i].y >> Matrix[i].data;
    }

    int num[M];
    for (int i = 0; i < M; i++)
    {
    
    
        num[i] = 0;
    }
    for (int i = 0; i < NUM; i++)
    {
    
    
        num[Matrix[i].y - 1]++;
    }
    cout << "num:";
    for (int i = 0; i < M; i++)
    {
    
    
        cout << num[i] << ",";
    }
    cout << endl;

    int cpot[M];
    cpot[0] = 0;
    for (int i = 1; i < M; i++)
    {
    
    
        cpot[i] = cpot[i - 1] + num[i - 1];
    }
    cout << "cpot:";
    for (int i = 0; i < M; i++)
    {
    
    
        cout << cpot[i] + 1 << ",";
    }
    cout << endl;

    Node TransMatrix[NUM];//转置后矩阵
    int count = 0, flag;
    for (int i = 0; i < NUM; i++)
    {
    
    //以原矩阵作为依据
        flag = Matrix[i].y-1;//以列作为标志
        TransMatrix[cpot[flag]].x = Matrix[i].y;
        TransMatrix[cpot[flag]].y = Matrix[i].x;
        TransMatrix[cpot[flag]].data = Matrix[i].data;
        cpot[flag]++;//在列中相应的位置需要后移
    }

    for (int i = 0; i < NUM; i++)
    {
    
    
        cout << TransMatrix[i].x << "," << TransMatrix[i].y << "," << TransMatrix[i].data << endl;
    }
    return 0;
}

supplement

Attach two vectors, num and cpot, to
num[col]indicate the number of non-zero elements
cpot[col]in the col-th column of matrix M, indicating the proper position of the first non-zero element in the col-th column in M ​​in b.dataInsert picture description here

Guess you like

Origin blog.csdn.net/zhj12399/article/details/109329307