稀疏矩阵的压缩存储和运算
#include<stdio.h>
#define m 6
#define n 8
#define max 50
void CreateMatrix(int A[m][n],int B[50])
{ int i,j,k=0;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
if(A[i][j]!=0){
B[k]=i; k++;
B[k]=j; k++;
B[k]=A[i][j]; k++;
}
B[k]=-1;
}
void MatrixAdd(int A[max],int B[max],int C[max]){
int i=0,j=0,k=0;
while(A[i]!=-1 && B[j]!=-1){
if(A[i]==B[j]){
if(A[i+1]==B[j+1]){
C[k]=A[i];
C[k+1]=A[i+1];
C[k+2]=A[i+2]+B[j+2];
k=k+3;
i=i+3;
j=j+3;
}
else
if(A[i+1]<B[j+1]){
C[k]=A[i];
C[k+1]=A[i+1];
C[k+2]=A[i+2];
k=k+3;
i=i+3;
}
else{
C[k]=B[j];
C[k+1]=B[j+1];
C[k+2]=B[j+2];
k=k+3;
j=j+3;
}
}
else
if(A[i]<B[j]){
C[k]=A[i];
C[k+1]=A[i+1];
C[k+2]=A[i+2];
k=k+3;
i=i+3;
}
else{
C[k]=B[j];
C[k+1]=B[j+1];
C[k+2]=B[j+2];
k=k+3;
j=j+3;
}
}
if(A[i]==-1)
while(B[j]!=-1){
C[k]=B[j];
C[k+1]=B[j+1];
C[k+2]=B[j+2];
k=k+3;
j=j+3;
}
else
while(A[i]!=-1){
C[k]=A[i];
C[k+1]=A[i+1];
C[k+2]=A[i+2];
k=k+3;
i=i+3;
}
C[k]=-1;
}
int main(void){
int E[m][n],F[m][n],A[max],B[max],C[max];
int i,j,k;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
printf("请输入E[%d][%d]:",i,j);
scanf("%d",&E[i][j]);
}
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
printf("请输入与F[%d][%d]:",i,j);
scanf("%d",&F[i][j]);
}
CreateMatrix(E,A);
CreateMatrix(F,B);
MatrixAdd(A,B,C);
i=0;j=0;k=0;
printf("A的数组内容如下:\n");
while(A[i]!=-1){
printf("%5d,%5d,%5d\n",A[i],A[i+1],A[i+2]);
i=i+3;
}
printf("B的数组内容如下:\n");
while(B[j]!=-1){
printf("%5d,%5d,%5d\n",B[j],B[j+1],B[j+2]);
j=j+3;
}
printf("C的数组内容如下:\n");
while(C[k]!=-1){
printf("%5d,%5d,%5d\n",C[k],C[k+1],C[k+2]);
k=k+3;
}
}
推荐大家一个小巧轻便的C语言编译工具
点击连接