#define _CRT_SECURE_NO_WARNINGS
#include<queue>
#include<string>
#include<iostream>
#include<algorithm>
#include<vector>
#include<climits> // INT_MAX头文件
using namespace std;
const int maxn=100; //叶子节点的最大个数
struct huffmanNode {
int weight; //权值
char character; //字符
int parent; //初始化为0
int lchild;
int rchild;
} huffmanTree[2*maxn]; //下标0的位置不用
// 1~n为叶子节点
void searchMin2(int& a, int& b, int n) {//从1到
int min = INT_MAX;
for (int i = 1; i <= n; ++i) {
//没有父节点
if (huffmanTree[i].parent == 0 && huffmanTree[i].weight < min) {
min = huffmanTree[i].weight;
a = i;
}
}
min = INT_MAX; //找次小
for (int i = 1; i <= n; ++i) {
if (huffmanTree[i].parent == 0 && huffmanTree[i].weight < min && i != a) {
min = huffmanTree[i].weight;
b = i;
}
}
if (huffmanTree[a].weight == huffmanTree[b].weight && huffmanTree[a].character > huffmanTree[b].character)
swap(a, b);
}
//所有数组都从1开始计算
void HuffmanCode(int n, char* s, int* w,vector<string>&ans) {
int m = 2 * n - 1; //m为节点总个数
for (int i = 1; i <= n; ++i) { //1~n为叶子节点
//一开始皆为独立的节点
huffmanTree[i].parent = huffmanTree[i].lchild = huffmanTree[i].rchild = 0;
huffmanTree[i].weight = w[i];
huffmanTree[i].character = s[i];
}
for (int i = n + 1; i <= m; i++) { //开始选最小和次小,生成哈夫曼树
int a, b;
searchMin2(a, b, i - 1); //从当前节点前面的节点中找
huffmanTree[i].lchild = a;
huffmanTree[i].rchild = b;
huffmanTree[i].weight = huffmanTree[a].weight + huffmanTree[b].weight;
huffmanTree[i].parent = 0;
huffmanTree[i].character = huffmanTree[a].character;
huffmanTree[a].parent = huffmanTree[b].parent = i;
}
//生成字符串
int c, f, index = 0;
string temp(n+1, 'a');
for (int i = 1; i <= m; i++) { //把所有节点的weight置为0
huffmanTree[i].weight = 0;
}
while (m) {
if (huffmanTree[m].weight == 0) { //根节点开始算
huffmanTree[m].weight = 1; //标记左边已经走过
if (huffmanTree[m].lchild != 0) { //有左孩子
m = huffmanTree[m].lchild; //往左子树走
temp[index++] = '0'; //左子树为0
}
else if (huffmanTree[m].rchild == 0) { //没有右孩子
//temp[index] = '\0';
ans[m] = temp;
}
}
else if (huffmanTree[m].weight == 1) {
huffmanTree[m].weight = 2; //标记右边已经走过
if (huffmanTree[m].rchild != 0) { //有右子树
m = huffmanTree[m].rchild;
temp[index++] = '1';
}
}
else {
//huffmanTree[m].weight = 0;//???可以去掉
m = huffmanTree[m].parent;
--index;
}
}
}
int main() {
//1~n闭区间考虑
int n, w[maxn]; // w为权重数组
char s[maxn]; //对应字符
vector<string>ans;
while (scanf("%d", &n) != EOF) { //A为65
for (int i = 1; i <= n; i++) {
getchar();
scanf("%c %d", &s[i], &w[i]);
}
//进行哈夫曼编码
ans.resize(n + 1);
HuffmanCode(n, s, w, ans);
for (int i = 1; i <= n; ++i)
{
cout << s[i] << ":";
for (int j = 0; j < ans[i].size(); j++) {
if (ans[i][j] != 'a')
cout << ans[i][j];
}
cout << endl;
}
}
}
11-20
12-20
825
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-23
8万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-06
7505
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
02-12
6万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交