您的位置:首页 > 其它

稀疏矩阵的接压缩算法的实现

2009-02-05 22:38 417 查看
稀疏矩阵中存放的有用信息是相当少的,对于那些无用信息,我们可以把他压缩掉,从而可以节省存储空间,有效的利用存储空间。

#include <stdio.h>

//定义三元组,用来存放压缩后的信息
typedef struct tag_Tuple
{
int column; // 有效信息所在的行
int row; // 有效信息所在的列
int value; // 有效信息的值
struct tag_Tuple * next; // 指向下一个三元组

// 初始化三元组
tag_Tuple()
{
column = -1;
row = -1;
value = -1;
next = 0;
}
}Tuple;

// 对稀疏矩阵进行压缩
Tuple * compress(int * array , int column , int row)
{
Tuple * header = new Tuple;
header->column = column;
header->row = row;

for (int i = 0;i < column;i++)
{
for (int j = 0;j < row;j++)
{
if (array[i * row + j] != 0)
{
Tuple * elem = new Tuple;
elem->column = i;
elem->row = j;
elem->value = array[i * row + j];
for (Tuple * p = header;p->next;p = p->next);
p->next = elem;
}
}
}

return header;
}

// 对三元组进行解压缩
void uncompress(int * array , Tuple * tuple)
{
for (int i = 0;i < tuple->column;i++)
{
for (int j = 0;j < tuple->row;j++)
{
array[i * tuple->row + j] = 0;
}
}

for (Tuple * p = tuple->next;p;p = p->next)
{
array[p->column * tuple->row + p->row] = p->value;
}
}

int main(int argc, char* argv[])
{
int a[4][5] = {
{0,0,1,2,0},
{0,0,0,3,0},
{1,0,0,0,0},
{0,0,0,0,0}};

Tuple * tuple = compress(a[0] , 4, 5);

int b[4][5];
uncompress(b[0] , tuple);

for (int i = 0;i < tuple->column;i++)
{
for (int j = 0;j < tuple->row;j++)
{
printf("%d " , b[i][j]);
}
printf("/n");
}

for (Tuple * p = tuple;p;)
{
Tuple * tmp = p;
p = p->next;
delete tmp;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: