看清之后才看轻 发表于 2021-12-17 14:10:53

哈夫曼编码问题

本帖最后由 看清之后才看轻 于 2021-12-17 15:28 编辑

#include <stdio.h>
#include <stdlib.h>

#define n 7
#define m 2 * n - 1
#define maxval 100.0 //令maxval为最大值
typedef struct
{
    float weight;
    int parent, lchild, rchild;
} hufmtree;
typedef struct
{
    char bits;
    int start;
    char ch;
} Codetype;
Codetype code;
hufmtree tree;
void Huffman(hufmtree tree[])
{
    int i, j, p1, p2;
    float small1, small2, f;
    for (i = 0; i < m; i++)
    {
      tree.parent = 0; //初始化数组
      tree.lchild = 0;
      tree.rchild = 0;
      tree.weight = 0.0;
    }
    printf("Input every character's weight!\n");
    for (i = 0; i < n; i++)
    {
      scanf("%f", &f);
      tree.weight = f;
    }
    for (i = n; i < m; i++)
    {
      p1 = p2 = 0;
      small1 = small2 = maxval;
      for (j = 0; j <= i - 1; j++)
      {
            if (tree.parent == 0)
                if (tree.weight < small1)
                {
                  small2 = small1;
                  small1 = tree.weight;
                  p2 = p1;
                  p1 = j;
                  // printf("%d#",p1);
                }
                else if (tree.weight < small2)
                { //查找次小权,并用p2记录下标
                  small2 = tree.weight;
                  p2 = j;
                  // printf("%d#",p2);
                }
            tree.parent = tree.parent = i;
            tree.weight = tree.weight + tree.weight;
            tree.lchild = p1;
            tree.rchild = p2;
      }
    }
}
void HuffmanCode(hufmtree tree[])
{
    int i, j, p;
    for (i = 0; i < n; i++)
    {
      code.start = n - 1;
      j = i;
      p = tree.parent;
      while (p != 0)
      {
            // printf("%d %d#\n",i,j);
            if (tree.lchild == j)
                code.bits.start] = '0';
            else
                code.bits.start] = '1';
            code.start--;
            j = p;
            p = tree.parent;
      }
    }
}
void print_prefix_code(Codetype code[])
{
    for (int i = 0; i < n ; i++)
    {
      printf("%c's prefix code is ", code.ch);
      for (int j = 0; j < n; j++)
      {
            printf("%c", code.bits);
      }
      printf("\n");
    }
}
int main()
{
    printf("Input code character!Maxsize is 7.\n");
    for (int i = 0; i < n; i++)
    {
      scanf("%c", &code.ch);
    }
    Huffman(tree);
    HuffmanCode(tree);
    // for (int i = 0; i < n; i++)
    // {
    //   printf("%f ",tree.weight);
    // }
    print_prefix_code(code);

    return 0;
}
请问这个代码为什么输入ABCDEFG和0.40 0.30 0.15 0.05 0.04 0.03 0.03输出的编码不是唯一的?

Gacy 发表于 2021-12-17 15:36:25

数据结构 上学期的 学得人麻了{:10_266:}

阿萨德按时 发表于 2021-12-17 16:16:56

{:10_279:}

伽羅~ 发表于 2021-12-17 17:21:04

{:10_254:}

心驰神往 发表于 2021-12-18 08:04:30

100gram 发表于 2021-12-18 12:12:40

新手入场 发表于 2022-3-21 14:06:52

1
页: [1]
查看完整版本: 哈夫曼编码问题