7-10 三元组顺序表表示的稀疏矩阵转置Ⅱ (10分)
三元组顺序表表示的稀疏矩阵转置Ⅱ。设a和b为三元组顺序表变量,分别表示矩阵M和T。要求按照a中三元组的次序进行转置,并将转置后的三元组置入b中恰当的位置。
输入格式:
输入第1行为矩阵行数m、列数n及非零元素个数t。 按行优先顺序依次输入t行,每行3个数,分别表示非零元素的行标、列标和值。
输出格式:
按置入b中的顺序输出置入的位置下标,转置后的三元组行标、列标和值,数据之间用空格分隔,共t行。
输入样例1:
3 4 3
0 1 -5
1 0 1
2 2 2
输出样例1:
1 1 0 -5
0 0 1 1
2 2 2 2
正解:
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 100
#define OVERFLOW -2
#define OK 1
#define ERROR 0
typedef int DataType;
typedef struct
{
int row, col;
DataType value;
} Triple;
typedef struct
{
Triple data[MAXSIZE + 1]; // 一维数组
int rows, cols, nums; //矩阵的行数,列数和非零元素个数
} TSMatrix;
void Fast_TransposeTSMatrix (TSMatrix *A, TSMatrix *B)
{
if(B->nums)
{
int q = 0;
for(int col=0 ; col<A->cols; col++)
{
for(int p=0 ; p<A->nums; p++)
{
if(A->data[p].col == col)
{
B->data[q].row = A->data[p].col;
B->data[q].col = A->data[p].row;
B->data[q].value = A->data[p].value;
++q;
}
}
}
}
}
int main()
{
TSMatrix A,B;
int m,n,t;
scanf("%d %d %d",&m,&n,&t);
B.cols=A.rows=m;
B.rows=A.cols=n;
B.nums=A.nums=t;
for(int i=0; i<t; i++)
{
scanf("%d %d %d",&A.data[i].row, &A.data[i].col, &A.data[i].value);
}
Fast_TransposeTSMatrix(&A,&B);
for(int i=0; i<A.rows; i++)
{
for(int j=0;j<A.nums;j++)
{
if(B.data[j].col==i)
printf("%d %d %d %d\n",j,B.data[j].row,B.data[j].col,B.data[j].value);
}
}
}