我正在编写一个代码,其中包含诸如“abracadabra”之类的单词,并将其变成一个霍夫曼树。我理解霍夫曼树的原理,但我现在要抓住的是我将如何首先实施abracadabra。
我的老师告诉我们的方法是拥有两个独立的队列/阵列。第一个存储每个字母的数量,另一个存储字母的数量顺序(从最高到最低),当字母具有相同的值时,它们按字母顺序排序。
所以它会导致:5,2,2,1,1和a,b,r,c,d 我很确定他希望我们使用队列,但我不知道如何处理这段代码的简单部分..
任何帮助都会非常感激。
答案 0 :(得分:0)
我想不出你为什么被要求以这种形式写出来,但是在我的头脑中,我会这样做:
Initialise your two queues for counts and letters. For each letter in the input: Search for letter in letter-queue. If found set count to the corresponding value from the count-queue + 1 remove from both queues Else set count to 1 Add the letter and count into both queues in the correct place
完成后,您将按照正确的顺序排队以构建树。
感觉就像是在滥用队列,但如果这就是你被要求做的......
编辑:这是我可能实际上写的,没有队列等。
unsigned char input[]="abracadabra";
int counts[256];
memset(counts, 0, 256 * sizeof(int));
unsigned char i;
unsigned char *pt = input;
int max = 0;
while(i = *pt++)
{
counts[i]++;
if(counts[i] > max) max = counts[i];
}
while(max)
{
int nmax = 0;
for(int c = 0 ; c < 256 ; c++)
{
if(counts[c] < max && counts[c] > nmax) nmax = counts[c];
if(counts[c] == max)
{
printf("%c: %d\n", c, max);
}
}
max = nmax;
}