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

#include<bits/stdc++.h>
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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值