昨天我们班了一场小型的c++数据结构考试,然后博主平时上课也算认真学了吧,但是课后却没有去及时巩固,复习。有许多代码当时能敲出来,却因为缺乏重复的练习,因此敲代码的速度特别慢,而且许多地方都有一些bug。导致昨天有个很简单的huffman编码的问题我都没有解决。所以,今天我又花了一个小时的时间把这个题目再写了一遍,虽然一个小时还是比较长,但是毕竟是我自己独立完成的,没有看任何之前的代码,我也算满意了!
题目是这样的,有一个字符串,JAVAPROGRAMMING,希望你能够用不等长的HUFFMAN编码给它加密,最后得出它的WPL值。其实这道题目非常简单,根据字母出现的频率建立huffman树,最后用叶子结点的权值乘上它的length值,最后求和即可得到答案。真的非常非常非常简单!!!!!!!我是真的菜!!!!!!
最后贴上代码。因为在算法方面我现在还没有花时间,所以我的代码会有很多很多可以优化的地方,若有 有缘人看见我的代码,并且有任何建议,希望你能够提出来,我会及时修改,感谢你!!!
#include <iostream>
#include <cstring>
using namespace std;
int findParent(int i,struct element huffman[],int n);
void huffmanTree(int w[],struct element huffman[],int n);
void findMin(int& i1,int& i2,struct element huffman[],int n);
struct element
{
int parent;
int lChild;
int rChild;
int weight;
};
int main()
{
char str[20];
cin >> str;
int arr_big[27] = {0};
int count = 0;
for(int i = 0; i < strlen(str); i++)
{
for(int j = 0; j < 27; j++)
{
if(str[i] == char('A' + j))
{
arr_big[j] += 1;
if(arr_big[j] == 1)
{
count++;//记录一共出现了几个字母!
}
break;
}
}
}
int count2 = 0;
int arr_small[count] = {0};
for(int i = 0; i < 27; i++)
{
if(arr_big[i] != 0)
{
arr_small[count2++] = arr_big[i];
}
}
struct element huffman[2 * count - 1];
huffmanTree(arr_small,huffman,count);
int sum = 0;
for(int i = 0;i < count;i++)
{
int length = 0;
if(huffman[i].lChild == -1&&huffman[i].rChild == -1)
{
length = findParent(i,huffman,count);
sum += length * huffman[i].weight;
}
}
cout << sum;
return 0;
}
void huffmanTree(int w[],struct element huffman[],int n)
{
for(int i = 0; i < 2 * n - 1; i++)
{
huffman[i].parent = -1;
huffman[i].lChild = -1;
huffman[i].rChild = -1;
huffman[i].weight = -1;
}
for(int i = 0; i < n; i++)
{
huffman[i].weight = w[i];
}
for(int i = n; i < 2 * n - 1; i++)
{
int i1,i2;
findMin(i1,i2,huffman,n);
huffman[i].lChild = i1;
huffman[i].rChild = i2;
huffman[i1].parent = i;
huffman[i2].parent = i;
huffman[i].weight = huffman[i1].weight + huffman[i2].weight;
}
}
void findMin(int& i1,int& i2,struct element huffman[],int n)
{
int min = 9999999;
for(int i = 0; i < 2 * n - 1; i++)
{
if(huffman[i].weight == -1&&huffman[i].parent == -1)
{
break;
}
if(huffman[i].weight < min&&huffman[i].parent == -1)
{
min = huffman[i].weight;
i1 = i;
}
}
min = 999999;
for(int i = 0; i < 2 * n - 1; i++)
{
if(huffman[i].weight == -1)
{
break;
}
if(huffman[i].weight < min&&i != i1&&huffman[i].parent == -1)
{
min = huffman[i].weight;
i2 = i;
}
}
}
int findParent(int i,struct element huffman[],int n)
{
int length = 0;
if(huffman[i].parent == -1)
{
return 0;
}
length += (findParent(huffman[i].parent,huffman,n) + 1);
return length;
}