C/C++:三元组的快速转置矩阵算法

#include
using namespace std;
#define MaxSize 100

typedef struct {
	int row, col;       //行列
	int e;              //值
}Triple;

typedef struct {
	Triple data[MaxSize]; //三元组表数组
	int rows, cols, nums; //行列,非零元素个数
}TSMatrix;

void FastTran(TSMatrix* T, TSMatrix* M)
{
	int col, t, p;
	int num[MaxSize], cpot[MaxSize];
	cpot[1] = 1;
	if (M->nums)
	{
		for (col = 1; col <= T->cols; col++) //列元素个数初始化
			num[col] = 0;
		for (t = 1; t <= T->nums; t++) //各列元素个数
			num[T->data[t].col]++;

		for (col = 2; col <= T->cols; col++)    //起始位置要弄好
			cpot[col] = cpot[col - 1] + num[col - 1];

		for (p = 1; p <= T->nums; p++)
		{
			col = T->data[p].col;
			M->data[cpot[col]].row = T->data[p].col;
			M->data[cpot[col]].col = T->data[p].row;
			M->data[cpot[col]].e = T->data[p].e; 
			cpot[col]++; //起始位置+1
		}
	}

}

int main() 
{
	cin.tie(0);
	cout.tie(0);

	TSMatrix T;
	TSMatrix M;
	T.cols = 6; T.rows = 4; T.nums = 5;
	for (int i = 1; i <= 5; i++)
		cin >> T.data[i].row >> T.data[i].col >> T.data[i].e;

	cout << "转置前为:" << endl;
	for (int i = 1; i <= T.nums; i++) {
		cout << T.data[i].row << " " << T.data[i].col << " " << T.data[i].e << endl;;
	}

	FastTran(&T, &M);
	
	cout << "转置后为:" << endl;
	for (int i = 1; i <= T.nums; i++) {
		cout << M.data[i].row << " " << M.data[i].col << " " << M.data[i].e << endl;
	}
	exit(0);
}
//输入:1 2 14 1 5 -5 2 2 -7 3 1 36 3 4 28

你可能感兴趣的:(算法,c语言,c++)