DS:稀疏矩阵-三元组表

     用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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值