【数据结构】稀疏矩阵(快速转置算法)

稀疏矩阵

我们可以用一个三元组来表示矩阵中所有非0元素,以此来节省存储空间

例如:

row column value
0 0 4
1 2 7

稀疏矩阵的转置

我们可以直接将row和col两列中的元素交换位置,但这样得出的结果顺序是乱的(以row升序排列),所以我们可以采用以下方式

快速转置算法:

[0] [1] [2] [3] [4] [5]
rowSize
rowStart

第一列表示行号(从0开始)

rowSize收集该列号在稀疏矩阵三元组中出现多少次(因为转置,所以收集的是原矩阵列号)

rowStart表示该元素在转置三元组表中开始存放的位置

struct Triple
{
	int row;
	int col;
	int value;
};
void display(Triple* a,int terms)
{
	cout << "row" << " " << "col" << " " << "value" << endl;
	for (int i = 0; i < terms; i++)
	{
		cout << a[i].row << "    " << a[i].col << "    " << a[i].value;
		cout << endl;
	}
}
void FastTranspose(int terms,int col,Triple* a)
{
	Triple* Matrix = new Triple[terms];
	int* rowStart = new int[col];
	int* rowSize = new int[col];

	for (int i = 0; i < terms; i++)
	{
		
		rowSize[a[i].col]++;

	}
	for (int i = 0; i < col - 1; i++)
	{
		rowStart[i + 1] = rowStart[i] + rowSize[i];
	}
	for (int i = 0; i < terms; i++)
	{
		int j = rowStart[a[i].col];
		Matrix[j].row = a[i].col;
		Matrix[j].col = a[i].row;
		Matrix[j].value = a[i].value;
		rowStart[a[i].col]++;
	}
	display(Matrix,terms);
}
int main()
{
	Triple a[4];
	a[0].row = 0; a[0].col = 0; a[0].value = 15;
	a[1].row = 0; a[1].col = 4; a[1].value = 91;
	a[2].row = 1; a[2].col = 1; a[2].value = 11;
	a[3].row = 2; a[3].col = 1; a[3].value = 3;
	
	FastTranspose(4, 5,a);
}

你可能感兴趣的:(数据结构整理笔记,数据结构,矩阵,算法)