问题描述(Description)
Lempel-Ziv-Welch(LZW)编码算法是一种无误差压缩算法,将定长码字分配给变长信源符号序列。 现请尝试对输入单张灰度图像进行LZW编码。
输入(Input)
输入格式如下面的例子所示。
第一行为两个由空格隔开的数字M和N,分别代表图片的高和宽。
接下来M行,每行有N个数字,每个数字代表图片相应位置的灰度值,相邻的数字由空格隔开。
读取数据时要求以行优先的方式读取。
例:
4 4
39 39 126 126
39 39 126 126
39 39 126 126
39 39 126 126
输出(Output)
图片的LZW编码,相邻的码字用空格隔开。
#include <iostream>
#include <vector>
#include <iomanip>
#include <limits>
#include <math.h>
#include <map>
#include <string>
using namespace std;
void showImage(vector<vector<string>> &image_2d)
{
for (int i = 0; i < image_2d.size(); i++)
{
for (int j = 0; j < image_2d[0].size(); j++)
// 访问并且输出(左对齐)二维矩阵的各个元素
cout << image_2d[i][j] << " ";
cout << endl;
}
}
void showCode(vector<int> &code)
{
for (int i = 0; i < code.size(); i++)
{
cout << code[i] << " ";
}
cout << endl;
}
static vector<int> encode()
{
//初始化dictionary
int m, n;
int value;
cin >> m >> n;
int idleCode = 256;
map<string, int> dictionary;
for (int i = 0; i < idleCode; i++)
{
dictionary.insert(pair<string, int>(to_string(i), i));
}
string P = "";
string C = "";
string PC = "";
bool PC_in_dic = true;
vector<int> result = result;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
cin >> value;
C = to_string(value);
if (P.size())
{
PC = P + "-" + C;
}
else
{
PC = C;
}
// 操作
if (dictionary.count(PC))
{
P = PC;
// cout << "-[INFO] Yes, P=" << P << endl;
}
else
{
dictionary.insert(pair<string, int>(PC, idleCode));
idleCode += 1;
result.push_back(dictionary[P]);
P = C;
// cout << "-[INFO] No, P+C=" << PC << endl;
}
}
}
result.push_back(dictionary[P]);
return result;
}
int main()
{
vector<int> result;
result = encode();
// cout << "Result:" << endl;
showCode(result);
return 0;
}
/*
4 4
39 39 126 126
39 39 126 126
39 39 126 126
39 39 126 126
39 39 126 126 256 258 260 259 257 126
39 39 126 126 256 258 260 259 257 126
*/