案例
输入一个字符串,分别用普通ASCII编码(每个字符8bit)和Huffman编码,输出编码后
的长度,并计算出压缩比。
输入样例:
AAAAABCD
输出样例:
64 13 4.9
源码
#include<iostream>
using namespace std;
#include<queue>
#include<string>
#include <iomanip>
priority_queue<int, vector<int>, greater<int>>Q;
int main() {
cout << "请输入字符串:" << endl;
string s;
while (getline(cin, s) && s != "END") {
int t = 1;
for (int i = 0; i < (signed)s.size(); i++) {
if (s[i] == s[i + 1]) {
t++;
}
else {
Q.push(t);
t = 1;
}
}
int ans=0;
while (Q.size() > 1) {
int a = Q.top();
Q.pop();
int b = Q.top();
Q.pop();
Q.push(a + b);
ans += a + b;
}
double rate = (double)s.size() * 8 / (double)ans;
cout << fixed << setprecision(1);
cout << "ASCLL:" << 8 * s.size() << " Huffman:" << ans << " Compression rate:" << rate << endl;
}
system("pause");
return 0;
}
测试
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/68c22330eb29b3c6a198d0678b8e2a80.png)