主要是稀疏矩阵的创建、输出、转置和快速转置
include.h
#ifndef INCLUDE
#define INCLUDE
#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
#define OVERFLOW -2
#define OK 1
#define ERROR -1
#endif
Tri.h
#ifndef TRI
#define TRI
#define MAXSIZE 100
typedef int ElemType;
typedef int Status;
typedef struct{
int i,j;
ElemType e;
}Triple;
typedef struct{
Triple data[MAXSIZE+1];
int mu,nu,tu;
}TSMatrix;
Status CreateSMatrix(TSMatrix &M,int n,int m);
Status FastTransposeSMatrix(TSMatrix M,TSMatrix &T);
void Out(TSMatrix M);
Status TransposeSMatrix(TSMatrix M,TSMatrix &T);
#endif
main.cpp
#include <iostream>
#include"include.h"
#include"Tri.h"
int main() {
printf("请输入稀疏矩阵的三元组的排和列:\n");
int m,n;
TSMatrix M = {0};
TSMatrix T = {0};
scanf("%d %d",&m,&n);
CreateSMatrix(M,m,n);
Out(M);
FastTransposeSMatrix(M,T);
//TransposeSMatrix(M,T);
Out(T);
return 0;
}
Triple.cpp
#include"include.h"
#include"Tri.h"
Status CreateSMatrix(TSMatrix &M,int n,int m){
M.mu=n;
M.nu=m;
M.tu=1;
int k=1;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++){
scanf("%d",&k);
if(k!=0){
M.data[M.tu].i = i;
M.data[M.tu].j = j;
M.data[M.tu].e = k;
M.tu++;
}
}
return OK;
}
Status FastTransposeSMatrix(TSMatrix M,TSMatrix &T){
T.mu = M.nu;T.nu = M.mu;T.tu = M.tu;
int num[M.nu],cpot[M.mu],q,p,col,t;
if(T.tu){
for(col=1;col<=M.nu;++col) num[col]=0;
for(t=1;t<=M.tu;++t) ++num[M.data[t].j];
cpot[1]=1;
for(col=2;col<=M.nu;++col) cpot[col] = cpot[col-1]+num[col-1];
for(p=1;p<M.tu;++p){
col = M.data[p].j;
T.data[q].j = M.data[p].i;q=cpot[col];
T.data[q].i = M.data[p].j;T.data[q].j = M.data[p].i;
T.data[q].e = M.data[p].e; ++cpot[col];
}
}
return OK;
}
Status TransposeSMatrix(TSMatrix M,TSMatrix &T){
T.mu = M.nu;T.nu = M.mu;T.tu = M.tu;
int q=1,p=1;
for(int col =1;col<=M.nu;++col){
for(p=1;p<=M.tu;++p)
if(M.data[p].j==col){
T.data[q].i = M.data[p].j;
T.data[q].j = M.data[p].i;
T.data[q].e = M.data[p].e;
++q;
}
}
return OK;
}
void Out(TSMatrix M){
int k=1;
for(int i=1;i<=M.mu;i++)
{
for(int j=1;j<=M.nu;j++)
{
printf("%d\t",M.data[k].e);
k++;
}
printf("\n");
}
}
最后的话
代码仅做参考和本人的学习记录,请不要用于其他途径。
刚写博客不久,注释说明不全,请谅解,学艺不精,请指正。