# 最优前缀码问题

## 设计

typedef struct {
unsigned int weight;
unsigned int parent, lchild, rchild;
}HTNode, * HuffmanTree;

typedef char** HuffmanCode;

void Select(HuffmanTree* HT, int n, int* s1, int* s2);

void CreateHuffmanTree(HuffmanTree* HT, int* w, int n) {
int m = 0;
int i = 0;
int s1 = 0;
int s2 = 0;
if (n <= 1) {
return;
}
m = 2 * n - 1;
*HT = (HuffmanTree)malloc((m + 1) * sizeof(HTNode));
if (!*HT) {
exit(-1);
}
for (adjust = *HT + 1, i = 1; i <= n; ++adjust, ++i) {
adjust->weight = *(w + i - 1);
}
for (; i <= m; ++i, ++adjust) {
}
for (i = n + 1; i <= m; ++i) {
Select(HT, i - 1, &s1, &s2);
(*HT + s1)->parent = (*HT + s2)->parent = i;
(*HT + i)->lchild = s1;
(*HT + i)->rchild = s2;
(*HT + i)->weight = (*HT + s1)->weight + (*HT + s2)->weight;
}
}

int Min(HuffmanTree HT, int n) {
unsigned int f_min = 100;
int flag = 0;
for (int i = 1; i <= n; ++i) {
if ((HT + i)->weight < f_min && (HT + i)->parent == 0) {
f_min = (HT + i)->weight;
flag = i;
}
}
(HT + flag)->parent = 1;
return flag;
}

void Select(HuffmanTree* HT, int n, int* s1, int* s2) {
int tmp = 0;
*s1 = Min(*HT, n);
*s2 = Min(*HT, n);
if ((*HT + *s1)->weight > (*HT + *s2)->weight) {
tmp = *s1;
*s1 = *s2;
*s2 = tmp;
}
}

void HuffmanCoding(HuffmanTree HT, HuffmanCode* HC, int n) {
*HC = (HuffmanCode)malloc((n + 1) * sizeof(char*));
if (!*HC) {
exit(-1);
}
char* cd = (char*)malloc(n * sizeof(char));
if (!cd) {
exit(-1);
}
*(cd + n - 1) = '\0';
int start = 0;
for (int i = 1; i <= n; ++i) {
start = n - 1;
for (int c = i, f = (HT + i)->parent; f != 0; c = f, f = (HT + f)->parent) {
if ((HT + f)->lchild == c) {
*(cd + --start) = '0';
}
else {
*(cd + --start) = '1';
}
}
*(*HC + i) = (char*)malloc((n - start) * sizeof(char));
strcpy_s(*(*HC + i),strlen(cd+start)+1, cd + start);
}
free(cd);
}


## github源码

https://github.com/1651928813/Pepsi_juice/tree/master/%E5%AE%9E%E9%AA%8C%E5%8D%81%E4%B8%80

03-14 3709

05-18 21

05-18 18

05-12 75

11-24

08-23 1万+

05-16 160

05-14 2535

11-07 640

03-26 9万+

04-14 58万+

03-13 14万+

03-01 13万+

03-04 13万+

03-08 4万+

03-08 7万+

04-25 6万+

03-10 12万+

03-12 11万+

03-13 11万+

03-14 1万+

03-18 9085

03-19 3万+

03-19 8万+

03-19 3万+

03-22 4万+

03-24 3万+

03-25 3万+

05-08 5万+

03-25 9万+

03-27 1万+

03-29 21万+

03-29 10万+

03-30 16万+

05-28 5437

05-28 1万+

04-02 3122

04-02 4万+

04-06 7万+

04-09 8万+

04-09 2万+

05-17 7785

04-11 3万+

04-15 6万+

04-18 4万+

04-20 4万+

04-24 3万+

04-29 6674

04-30 9653

04-30 9141

05-01 4832

05-03 9146

05-16 5万+

05-06 1万+

05-08 4万+

05-10 2987

05-14 5934

05-14 1672

05-16 3269

05-16 1万+

05-20 662

05-18 7920

05-27 835

05-18 3165

05-19 1万+

05-21 6214

05-21 6211

05-27 4532

05-25 4489

05-23 6160

05-28 729

05-23 1340

05-24 7712

05-25 4696

05-25 3405

05-25 3684

#### 5月，我面试60多号人，才发现很多人没有这项能力

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试