Catalog
  1. 1. 数据结构实验三之矩阵压缩和释放,应用多种方法。
数据结构实验三之矩阵的压缩和解压

数据结构实验三之矩阵压缩和释放,应用多种方法。

#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
int a[200][200];
int c[200][200];
const int maxn = 200 * 201 / 2;
int b[maxn];
int k = 0;
int n;
void two_circle_compression() {/*二重循环压缩矩阵*/
cout << "二重循环压缩后的结果" << endl;
k = 0;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= i; j++)
{
if (i >= j) {
b[i * (i - 1) / 2 + j - 1] = a[i][j];
k++;
}

else {
b[j * (j - 1) / 2 + i - 1] = a[i][j];
k++;
}

}
}
void one_circle_compression() {/*一重循环压缩矩阵*/
cout << "一重循环压缩后的结果" << endl;
int j = 1;
int i = 1;
k = 0;
for (; i <= n; )
{
if (i >= j) {
b[i * (i - 1) / 2 + j - 1] = a[i][j];
k++;
}
else {
b[j * (j - 1) / 2 + i - 1] = a[i][j];
k++;
}
if (i == j) {
j = 1;
i++;
}
else j++;
}
}
void release1() {
cout << "一重循环解压的结果" << endl;
for (int x = 0; x < k; x++)
{
int i = 1;
int j = 1;

for (; i <= n; )
{
if (x == i * (i - 1) / 2 + j - 1)
{
if (i == j) c[i][j] = b[x];
else {
c[i][j] = b[x];
c[j][i] = b[x];
}

break;
}
if (i == j) {
i++;
j = 1;
}
else j++;


}
}
}
void release2() {
cout << "二重循环解压的结果" << endl;
for (int x = 0; x < k; x++)
{
int flag = 0;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
if (x == i * (i - 1) / 2 + j - 1)
{
if (i == j) c[i][j] = b[x];
else {
c[i][j] = b[x];
c[j][i] = b[x];
}
flag = 1;
break;
}

}
if (flag == 1) break;
}
}
}
void release3() {/*矩阵解压*/
cout << "公式解压后的结果" << endl;
float i;
for (int x = 0; x < k; x++)
{
i = sqrt(2 * (x + 1) + 0.25) - 0.5;
i = ceil(i);
int i_ = i;
int j = x + 1 - i * (i - 1) / 2;
if (i == j)
c[i_][j] = b[x];
else {
c[i_][j] = b[x];
c[j][i_] = b[x];
}
}


}
void print_compression() {/*压缩后的矩阵打印*/
for (int i = 0; i < k; i++)
cout << b[i] << " ";
cout << endl;
}

void print_realease() {/*解压后的矩阵打印*/

for(int i = 1; i<= n;i++)
for (int j = 1; j <= n; j++) {
if (j != n)
cout << c[i][j] << " ";
else cout << c[i][j];
if (j == n)cout << endl;
}
}
int main() {
cout << "请输入矩阵的阶数:";
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
cin >> a[i][j];

one_circle_compression();//一重循环压缩
print_compression();//打印
two_circle_compression();//二重循环压缩
print_compression();//打印
release1();//一重循环解压
print_realease();//打印
release2();//二重循环解压
print_realease();//打印
release3();//公式解压矩阵
print_realease();//打印

}

Author: superzhaoyang
Link: http://yoursite.com/2019/10/13/数据结构实验三之矩阵的压缩和解压/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
  • 支付宝

Comment