Problem Description
字符的编码方式有多种,除了大家熟悉的ASCII编码,哈夫曼编码(Huffman Coding)也是一种编码方式,它是可变字长编码。该方法完全依据字符出现概率来构造出平均长度最短的编码,称之为最优编码。哈夫曼编码常被用于数据文件压缩中,其压缩率通常在20%~90%之间。你的任务是对从键盘输入的一个字符串求出它的ASCII编码长度和哈夫曼编码长度的比值。
Input
输入数据有多组,每组数据一行,表示要编码的字符串。
Output
对应字符的
ASCII
编码长度
la
,
huffman
编码长度
lh
和
la/lh
的值
(
保留一位小数
)
,数据之间以空格间隔。
Example Input
AAAAABCD THE_CAT_IN_THE_HAT
Example Output
64 13 4.9 144 51 2.8
#include <stdio.h> #include <stdlib.h> #include <string.h> #define SUM 10 typedef int Elemtype; typedef struct BiTnode { Elemtype data; struct BiTnode *lchild, *rchild, *next, *parent; } BiTnode, *BiTree; typedef struct { BiTree front; BiTree rear; int len; } Queue; Queue q; int wl; void Sort(int a[], int n); void Init(); void EnQueue(int x); BiTree OutQueue(); void Insert(BiTree root); BiTree Create(); int Path(BiTree p); void WPL(BiTree p); int main() { int n, i, length; char s[10010]; while(~scanf("%s", s)) { n = 0; wl = 0; int la; int b[150] = {0}; int a[150]; length = strlen(s); la = 8 * length; for(i = 0; i < length; i++) b[s[i]]++; for(i = 0; i < 150; i++) if(b[i] != 0) a[n++] = b[i]; Sort(a, n); Init(); for(i = 0;i < n; i++) EnQueue(a[i]); BiTree root; root = Create(); WPL(root); printf("%d %d %.1lf\n", la, wl, 1.0*la/wl); } return 0; } void Sort(int a[], int n) { int i, j; for(i = 0; i < n-1; i++) for(j = 0; j < n - i - 1; j++) { if(a[j] > a[j+1]) { int t = a[j]; a[j] = a[j+1]; a[j+1] = t; } } } void Init() { q.front = (BiTree)malloc(sizeof(BiTnode)); q.front -> next = NULL; q.rear = q.front; q.len = 0; } void EnQueue(int x) { BiTree p; p = (BiTree)malloc(sizeof(BiTnode)); p -> next = NULL; p -> rchild = NULL; p -> lchild = NULL; p -> parent = NULL; p -> data = x; q.rear -> next = p; q.rear = p; q.len++; } BiTree OutQueue() { if(q.len == 1) { BiTree p; p = q.front -> next; q.front = NULL; q.rear = q.front; q.len--; return p; } else { BiTree p, t; t = p = q.front -> next; p = p -> next; q.front -> next = p; q.len--; return t; } } void Insert(BiTree root) { BiTree p, t; p = q.front -> next; t = q.front; while(root -> data > p -> data) { p = p -> next; t = t -> next; if(!p) break; } if(p) { root -> next = p; t -> next = root; } else { q.rear -> next = root; q.rear = root; } q.len++; } BiTree Create() { if(q.len > 1) { BiTree root, t1, t2; root=(BiTree)malloc(sizeof(BiTnode)); root -> next = NULL; root -> parent = NULL; t1 = OutQueue(); t2 = OutQueue(); root -> lchild = t1; root -> rchild = t2; root -> data = t1 -> data + t2 -> data; t1 -> parent = root; t2 -> parent = root; if(q.len == 0) return root; else { Insert(root); Create(); } } } int Path(BiTree p) { int l = 0; int x = p -> data; while(p -> parent) { p = p -> parent; l++; } return l * x; } void WPL(BiTree p) { if(!p -> lchild && !p -> rchild) { int e = Path(p); wl += e; } else { if(p -> lchild) WPL(p -> lchild); if(p -> rchild) WPL(p -> rchild); } }