-
【问题描述】
稀疏矩阵的存储不宜用二维数组存储每个元素,那样的话会浪费很多的存储空间。所以可以使用一个一维数组存储其中的非零元素。这个一维数组的元素类型是一个三元组,由非零元素在该稀疏矩阵中的位置(行号和列号对)以及该元组的值构成。而矩阵转置就是将矩阵行和列上的元素对换。
请你实现一个快速的对稀疏矩阵进行转置的算法。
【输入形式】
输入的第一行是两个整数r和c(r<200, c<200, r*c <= 12500),分别表示一个包含很多0的稀疏矩阵的行数和列数。接下来有r行,每行有c个整数,用空格隔开,表示这个稀疏矩阵的各个元素。
【输出形式】
输出为读入的稀疏矩阵的转置矩阵。输出共有c行,每行有r个整数,每个整数后输出一个空格。请注意行尾输出换行。
【样例输入】
6 7
0 12 9 0 0 0 0
0 0 0 0 0 0 0
-3 0 0 0 0 14 0
0 0 24 0 0 0 0
0 18 0 0 0 0 0
15 0 0 -7 0 0 0
【样例输出】
0 0 -3 0 0 15
12 0 0 0 18 0
9 0 0 24 0 0
0 0 0 0 0 -7
0 0 0 0 0 0
0 0 14 0 0 0
0 0 0 0 0 0
#include<stdio.h>
#define MAXSIZE 10
typedef struct{
int row,col;
int e;
}Triple;
typedef struct{
Triple data[MAXSIZE+1];
int m,n,len;
}Matrix;
void TranposeMatrix(Matrix A,Matrix *B)
{
int i,j,k;
B->m=A.n;
B->n=A.m;
B->len=A.len;
for(k=1;k<=A.n;i++){
j=1;
for(i=1;i<=A.len;i++){
if(A.data[i].col==j){
B->data[j].col=A.data[i].row;
B->data[j].row=A.data[i].col;
B->data[j].e=A.data[i].e;
j++;
}
}
}
}
void FastTramposeMatrix(Matrix A,Matrix *B)
{
int pos[MAXSIZE],num[MAXSIZE];
int i,j,k;
B->len=A.len;B->m=A.n;B->n=A.m;
for(i=1;i<=A.n;i++)
num[i]=0;
for(j=1;i<=A.len;i++)
num[A.data[j].col]++;
pos[1]=1;
for(k=2;k<=A.n;i++)
pos[k]=pos[k-1]+num[k-1];
for(i=1;i<=A.len;i++){
j=A.data[i].col;
k=pos[j];
B->data[k].col=A.data[i].row;
pos[j]++;
}
}
#include<iostream>
#define MAXSIZE 1000
using namespace std;
typedef struct{
int row,col;
int e;
}Triple;
typedef struct{
Triple data[MAXSIZE+1];
int m,n,len;
}Matrix;
void Create(Matrix *a)
{
int i,j,k;
a->len=0;
cin>>a->m>>a->n;
for(i=1;i<=a->m;i++){
for(j=1;j<=a->n;j++){
cin>>k;
if(k){
a->len++;
a->data[a->len].row=i;
a->data[a->len].col=j;
a->data[a->len].e=k;
}
}
}
}
void Tranpose(Matrix a,Matrix *b)
{
int i,j,k;
b->len=a.len;
b->m=a.n;
b->n=a.m;
int pos[MAXSIZE],num[MAXSIZE];
for(i=1;i<=a.n;i++)
num[i]=0;
for(i=1;i<=a.len;i++)
num[a.data[i].col]++;
pos[1]=1;
for(j=2;j<=a.n;j++)
pos[j]=pos[j-1]+num[j-1];
for(i=1;i<=a.len;i++){
j=a.data[i].col;
k=pos[j];
b->data[k].col=a.data[i].row;
b->data[k].row=a.data[i].col;
b->data[k].e=a.data[i].e;
pos[j]++;
}
}
void Print(Matrix b)
{
int i,j,k=1;
for(i=1;i<=b.m;i++){
for(j=1;j<=b.n;j++){
if(i==b.data[k].row&&j==b.data[k].col){
cout<<b.data[k].e<<" ";
k++;
}
else{
cout<<0<<" ";
}
}
cout<<endl;
}
}
int main()
{
Matrix a,b;
Create(&a);
Tranpose(a,&b);
Print(b);
return 0;
}