好友
阅读权限10
听众
最后登录1970-1-1
|
本帖最后由 Etan76 于 2023-10-28 18:22 编辑
为什么我的输出前面会有队列一个符号?下面是我使用过的头文件名
#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define MAXBIT 10
#define MAXVALUE 1000
typedef struct HNode {
int weight; // 权重
int lchild;
int rchild;
int parent;
} HNode, *HTree;
// 构建最优二叉树
HTree HuffmanTree(int* w, int n) {
int m, m1, m2, x1, x2, i, j;
HTree ht;
HNode* p;
if (n <= 1) {
return NULL;
}
m = 2 * n - 1;
ht = new HNode[m];
if (ht == NULL) return ht;
for (p = ht, i = 0; i < n; ++i, ++p, ++w) {
p->weight = *w;
p->rchild = -1;
p->lchild = -1;
p->parent = -1;
}
for (; i < m; ++i) {
p->weight = 0;
p->rchild = -1;
p->lchild = -1;
p->parent = -1;
}
for (i = n; i < m; ++i) {
m1 = m2 = MAXVALUE;
x1 = x2 = 0;
for (j = 0; j < i; ++j) {
if (ht[j].parent == -1 && ht[j].weight < m1) {
m2 = m1;
x2 = x1;
m1 = ht[j].weight;
x1 = j;
}
else if (ht[j].parent == -1 && ht[j].weight < m2) {
m2 = ht[j].weight;
x2 = j;
}
}
ht[x1].parent = i;
ht[x2].parent = i;
ht.lchild = x1;
ht.rchild = x2;
ht.weight = m1 + m2;
}
return ht;
}
// 获取哈夫曼编码
void getHuffmanCode(HTree ht, int n, vector<string>& huffmanCode) {
for (int i = 0; i < n; ++i) {
string code = "";
int child = i;
int parent = ht[child].parent;
while (parent != -1) {
if (ht[parent].lchild == child) {
code += "0";
}
else {
code += "1";
}
child = parent;
parent = ht[child].parent;
}
reverse(code.begin(), code.end()); // 反转字符串,得到正确的哈夫曼编码
huffmanCode.push_back(code);
}
}
int main() {
int n;
cin >> n;
int* weights = new int[n];
for (int i = 0; i < n; ++i) {
cin >> weights;
}
HTree ht = HuffmanTree(weights, n); // 构建最优二叉树
vector<string> huffmanCode;
getHuffmanCode(ht, n, huffmanCode); // 获取哈夫曼编码
int wpl = 0; // 带权路径长度
for (int i = 0; i < n; ++i) {
wpl += weights * huffmanCode.length();
}
cout << wpl << endl; // 输出带权路径长度
sort(huffmanCode.begin(), huffmanCode.end()); // 按字典序排序哈夫曼编码
for (int i = 0; i < n; ++i) {
cout << huffmanCode << endl; // 输出哈夫曼编码
}
delete[] weights;
delete[] ht;
return 0;
} |
-
|
发帖前要善用【论坛搜索】功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。 |
|
|
|
|