编写c++程序实现利用三元组存储实现矩阵的转置算法
时间: 2024-05-25 16:19:31 浏览: 54
C++矩阵转置实现
5星 · 资源好评率100%
#include <stdio.h>
#define MAX_SIZE 100
typedef struct {
int row;
int col;
int val;
} Triple;
// 转置函数
void transpose(Triple *a, Triple *b) {
int m = a[0].row, n = a[0].col, t = a[0].val;
int col, p, q;
int num[n + 1], cpot[n + 1];
b[0].row = n;
b[0].col = m;
b[0].val = t;
if (t > 0) {
for (col = 1; col <= n; col++) num[col] = 0;
for (p = 1; p <= t; p++) num[a[p].col]++;
cpot[1] = 1;
for (col = 2; col <= n; col++) cpot[col] = cpot[col - 1] + num[col - 1];
for (p = 1; p <= t; p++) {
col = a[p].col;
q = cpot[col];
b[q].row = a[p].col;
b[q].col = a[p].row;
b[q].val = a[p].val;
cpot[col]++;
}
}
}
// 打印函数
void printMatrix(Triple *a) {
int m = a[0].row, n = a[0].col, t = a[0].val;
int i, j, k = 1;
for (i = 1; i <= m; i++) {
for (j = 1; j <= n; j++) {
if (k <= t && a[k].row == i && a[k].col == j) {
printf("%d ", a[k].val);
k++;
} else {
printf("0 ");
}
}
printf("\n");
}
}
int main() {
Triple a[MAX_SIZE], b[MAX_SIZE];
int m, n, t, i;
printf("请输入矩阵的行数、列数和非零元素个数:\n");
scanf("%d%d%d", &m, &n, &t);
a[0].row = m;
a[0].col = n;
a[0].val = t;
printf("请输入矩阵的三元组:\n");
for (i = 1; i <= t; i++) {
scanf("%d%d%d", &a[i].row, &a[i].col, &a[i].val);
}
printf("原矩阵为:\n");
printMatrix(a);
transpose(a, b);
printf("转置后的矩阵为:\n");
printMatrix(b);
return 0;
}
阅读全文