数据结构——稀疏矩阵

快速转置O(n+m)

我表示看不懂网上为什么都要copt[1]=1而且还要从2开始遍历,因此我改了一下,从下标0开始

M fast(M a, M b)
{
    b.cols = a.rows;
    b.rows = a.cols;
    b.num = a.num;
    int copt[N], num[N];
    for (int i = 0; i < a.num; i++)
    {
        num[a.data[i].col]++; // 计数
    }
    copt[0] = 0;
    for (int i = 1; i < a.num; i++)
    {
        copt[i] = copt[i - 1] + num[i - 1];
    }
    for (int i = 0; i < a.num; i++)
    {
        int t = a.data[i].col;
        t = copt[t];
        b.data[t].col = a.data[i].row;
        b.data[t].row = a.data[i].col;
        b.data[t].data = a.data[i].data;
        copt[a.data[i].col]++;
    }

    return b;
}

全部代码(存储,打印,转置)

#include <bits/stdc++.h>
using namespace std;
const int N = 10001;
typedef struct element
{
    int row, col, data;
} element;
typedef struct Metrix
{
    int rows, cols;
    element data[N];
    int num;

} M;
void init(M *a, int r, int c)
{
    a->rows = r;
    a->cols = c;
    a->num = 0;
}
void insert(M *a, int r, int c, int data)
{
    int t = a->num;
    a->data[t].col = c;
    a->data[t].row = r;
    a->data[t].data = data;
    a->num++;
}
void prt(M a)
{
    int k = 0;
    for (int i = 0; i < a.rows; i++)
    {
        for (int j = 0; j < a.cols; j++)
        {
            if (k < a.num && a.data[k].row == i && a.data[k].col == j)
            {
                cout << a.data[k].data << " ";
                k++;
            }
            else
                cout << "0 ";
        }
        cout << endl;
    }
}
M fast(M a, M b)
{
    b.cols = a.rows;
    b.rows = a.cols;
    b.num = a.num;
    int copt[N], num[N];
    for (int i = 0; i < a.num; i++)
    {
        num[a.data[i].col]++; // 计数
    }
    copt[0] = 0;
    for (int i = 1; i < a.num; i++)
    {
        copt[i] = copt[i - 1] + num[i - 1];
    }
    for (int i = 0; i < a.num; i++)
    {
        int t = a.data[i].col;
        t = copt[t];
        b.data[t].col = a.data[i].row;
        b.data[t].row = a.data[i].col;
        b.data[t].data = a.data[i].data;
        copt[a.data[i].col]++;
    }

    return b;
}
int main()
{
    M matrix;
    M b;
    init(&matrix, 5, 5);
    insert(&matrix, 0, 1, 5);
    insert(&matrix, 0, 3, 7);
    insert(&matrix, 1, 0, 8);
    insert(&matrix, 1, 2, 9);
    insert(&matrix, 2, 2, 1);
    insert(&matrix, 3, 1, 2);
    prt(matrix);
    b = fast(matrix, b);
    prt(b);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值