您的位置:首页 > 其它

DS:稀疏矩阵-三元组表

2017-07-26 14:54 183 查看
     用c++写了下,当作是练习吧XD

// STACK.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<time.h>
#include<string.h>
#define I 3
#define J 4
#define maxsize I*J
struct triple{
int i,j,value;
};
struct tritable{
triple data[maxsize];
int mu,nu,tu;
}tsmtype;

int create(int **&b){
b=(int **)malloc(sizeof(int)*J);
for(int i = 0;i<I; i++)
{
b[i]=(int *)malloc(sizeof(int)*I);
}

srand(time(NULL));
return 0;}

void initary(int **&b)
{ putchar(' ');putchar(' ');
for(int k = 0;k<J;k++)
{
printf("%d\t",k);
}putchar('\n');
for( int i = 0;i<I; i++)
{
printf("%d:",i);
for(int j = 0;j<J;j++)
{
if(rand()%2==0)b[i][j]=0;
else b[i][j]=i*j;
printf("%d\t",b[i][j]);
}putchar('\n');
}
}
int compress(int **&b)
{int k=0;
for( int i = 0;i<I; i++)
{ for(int j = 0;j<J;j++)
{
if(b[i][j]!=0)
{
tsmtype.data[k].i=i;
tsmtype.data[k].j=j;
tsmtype.data[k].value=b[i][j];
k++;
}
}
}
tsmtype.mu=I;
tsmtype.nu=J;
tsmtype.tu=k;
for(i=0;i<k;i++)
{
printf("%d:%d %d %d\n",i,tsmtype.data[i].i,tsmtype.data[i].j,tsmtype.data[i].value);
}

return 0;}

void displytriple(tritable * &A)
{
int k=0;
for( int i = 0;i<A->mu; i++)
{
printf("%d:",i);
for(int j = 0;j<A->nu;j++)
{
if(i==A->data[k].i&&j==A->data[k].j){printf("%d\t",A->data[k].value);k++;}
else printf("0\t");
}putchar('\n');
}
putchar('\n');
}
int rvsetriple(tritable * &A)
{
int k=0;
A=(tritable *) malloc(sizeof(tritable));
A->mu=tsmtype.nu;
A->nu=tsmtype.mu;
A->tu=tsmtype.tu;
for(int i=0;i<J;i++)
{
for(int j=0;j<tsmtype.tu;j++)
{
if(i==tsmtype.data[j].j)
{
A->data[k].i=tsmtype.data[j].j;
A->data[k].j=tsmtype.data[j].i;
A->data[k].value=tsmtype.data[j].value;
k++;

}
}
}

for(i=0;i<k;i++)
{
printf("%d:%d %d %d\n",i,A->data[i].i,A->data[i].j,A->data[i].value);
}

return 0;
}
int main()
{
int **b;
create(b);
puts("create array:");
initary(b);
puts("compress the array to triple:");
compress(b);
puts("display using the triple:");
tritable * A=&tsmtype;
displytriple(A);
puts("reverse the triple");
tritable * B;
rvsetriple(B);
displytriple(B);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: