|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 看清之后才看轻 于 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[n];
- int start;
- char ch;
- } Codetype;
- Codetype code[n];
- hufmtree tree[2 * n - 1];
- void Huffman(hufmtree tree[])
- {
- int i, j, p1, p2;
- float small1, small2, f;
- for (i = 0; i < m; i++)
- {
- tree[i].parent = 0; //初始化数组
- tree[i].lchild = 0;
- tree[i].rchild = 0;
- tree[i].weight = 0.0;
- }
- printf("Input every character's weight!\n");
- for (i = 0; i < n; i++)
- {
- scanf("%f", &f);
- tree[i].weight = f;
- }
- for (i = n; i < m; i++)
- {
- p1 = p2 = 0;
- small1 = small2 = maxval;
- for (j = 0; j <= i - 1; j++)
- {
- if (tree[j].parent == 0)
- if (tree[j].weight < small1)
- {
- small2 = small1;
- small1 = tree[j].weight;
- p2 = p1;
- p1 = j;
- // printf("%d#",p1);
- }
- else if (tree[j].weight < small2)
- { //查找次小权,并用p2记录下标
- small2 = tree[j].weight;
- p2 = j;
- // printf("%d#",p2);
- }
- tree[p1].parent = tree[p2].parent = i;
- tree[i].weight = tree[p1].weight + tree[p2].weight;
- tree[i].lchild = p1;
- tree[i].rchild = p2;
- }
- }
- }
- void HuffmanCode(hufmtree tree[])
- {
- int i, j, p;
- for (i = 0; i < n; i++)
- {
- code[i].start = n - 1;
- j = i;
- p = tree[i].parent;
- while (p != 0)
- {
- // printf("%d %d#\n",i,j);
- if (tree[p].lchild == j)
- code[i].bits[code[i].start] = '0';
- else
- code[i].bits[code[i].start] = '1';
- code[i].start--;
- j = p;
- p = tree[p].parent;
- }
- }
- }
- void print_prefix_code(Codetype code[])
- {
- for (int i = 0; i < n ; i++)
- {
- printf("%c's prefix code is ", code[i].ch);
- for (int j = 0; j < n; j++)
- {
- printf("%c", code[i].bits[j]);
- }
- printf("\n");
- }
- }
- int main()
- {
- printf("Input code character!Maxsize is 7.\n");
- for (int i = 0; i < n; i++)
- {
- scanf("%c", &code[i].ch);
- }
- Huffman(tree);
- HuffmanCode(tree);
- // for (int i = 0; i < n; i++)
- // {
- // printf("%f ",tree[i].weight);
- // }
- print_prefix_code(code);
- return 0;
- }
复制代码
请问这个代码为什么输入ABCDEFG和0.40 0.30 0.15 0.05 0.04 0.03 0.03输出的编码不是唯一的? |
-
-
|