#include <iostream>
#include <stdio.h>
using namespace std;
#define MAXSIZE 1024
#define ElemType int
#define Status int
// 三元组
typedef struct Triple{
int i, j; // i j
ElemType e; // 值
}Triple;
// 由三元组组成的表
typedef struct TSMatrix{
Triple data[MAXSIZE + 1]; // 在表中对应位置的三元组值
int nu, mu, tu; // nu:行数,mu:列数,tu:元素总数
}TSMatrix;
// 快速转置矩阵
void FastTransposeMatrix(TSMatrix& M, TSMatrix& N)
{
// 1.首先行列对换
N.nu = M.mu;
N.mu = M.nu;
N.tu = M.tu;
if (N.tu)
{
// num:下标表示元素在表中哪一个列,对应的值表示该列有几个元素(比如 第一列有二个元素:num[1] = 2)
// copt:下标表示列数,对应的值为该列第一个元素在转置后的表中对应的位置(比如 第二列第一个元素在位置3:copt[2] = 3)
int num[100] = {0};
int copt[100] = {0};
// 遍历M,得到每一列有几个元素
for (int i = 1; i <= M.tu; ++i)
{
++num[M.data[i].j];
}
// col:对应元素所在的列值;
int col;
// 第一列第一个元素明显为1 所以置copt[1]为1
copt[1] = 1;
// 从第二列开始,找到每列第一个元素所对应的位置
for (col = 2; col <= M.mu; ++col)
{
copt[col] = copt[col - 1] + num[col - 1];
}
// pos 暂时存放元素转置后对应的位置
int pos;
// 遍历M
for (int tmp = 1; tmp <= M.tu; ++tmp)
{
// 得到元素对应的列值
col = M.data[tmp].j;
// 找到该元素在新表中的位置
pos = copt[col];
// 转置
N.data[pos].i = M.data[tmp].j;
N.data[pos].j = M.data[tmp].i;
N.data[pos].e = M.data[tmp].e;
// 该列在copt中记录+1
++copt[col];
}
}
return;
}
int main()
{
TSMatrix M; // 原三元表
TSMatrix N; // 快速转置后的三元表
cout << "please input M Matrix:" << endl;
cout << "please input how many row and how many col : ";
cin >> M.nu >> M.mu;
cout << "input how many Elem : ";
cin >> M.tu;
cout << "input the i and j and value : ";
for (int i = 1; i <= M.tu; ++i)
{
cin >> M.data[i].i >> M.data[i].j >> M.data[i].e;
}
FastTransposeMatrix(M, N);
cout << "after Fast Transpose the Matrix's row is " << M.nu << ", col is " << M.mu << ", amount is " << M.tu << endl;
cout << "the value is " << endl;
for (int j = 1; j <= N.tu; ++j)
{
printf("%d %d %d\n", N.data[j].i, N.data[j].j, N.data[j].e);
}
return 0;
}
稀疏矩阵三元组的快速转置
最新推荐文章于 2023-10-30 11:08:50 发布