标签:char its 哈夫曼 class printf highlight encoding amp parent
#include <stdlib.h> #include <stdio.h> #include <string.h> typedef struct HuffmanTree { int weight; int parent, lchild, rchild; }HuffmanTree; typedef struct CodeNode { int ch; char bits[4+1]; }CodeNode; void SelectMin(HuffmanTree tree[], int len, int * pos1, int* pos2) { int min=255; int i, j; *pos1=0; *pos2=0; for(i=0; i<len; i++) { if(tree[i].parent==-1) if(min>tree[i].weight) { min=tree[i].weight; *pos1=i; } } min=255; for(j=0; j<len; j++) { if(j==*pos1) continue; if(tree[j].parent==-1) if(min>tree[j].weight) { min=tree[j].weight; *pos2=j; } } } void CreateHuffmanTree(HuffmanTree tree[], int n) { int m=2*n; int i; for(i=n; i<m-1; i++) { int pos1, pos2; HuffmanTree node; SelectMin(tree, i, &pos1, &pos2); printf("pos1=%d,pos2=%d\n", pos1, pos2); node.weight=tree[pos1].weight+tree[pos2].weight; tree[pos1].parent=i; tree[pos2].parent=i; node.lchild=pos1; node.rchild=pos2; node.parent=-1; tree[i]=node; } } void HuffmanEncoding(HuffmanTree tree[]) { int c, p, i; int start; char cd[4+1]; cd[4]=‘\0‘; for(i=0; i<4; i++) { printf("\n"); printf("%d",tree[i].weight); printf(":"); start=4; c=i; while((p=tree[c].parent)!=-1) { if(tree[p].lchild==c) { cd[--start]=‘0‘; } else { cd[--start]=‘1‘; } c=p; } printf(&cd[start]); } } int main(int argc, char* argv[]) { HuffmanTree tree[4*2]; int i, j; for(i=0; i<4; i++) { tree[i].lchild=-1; tree[i].rchild=-1; tree[i].parent=-1; } printf("请输入哈夫曼树叶子结点的权值: \n"); for(i=0; i<4; i++) //读入叶子结点的权值 { int weight; scanf("%d",&weight); tree[i].weight=weight; } CreateHuffmanTree(tree, 4); for(j=0; j<2*4-1; j++) { printf("tree[%d]:weight=%d \n", j, tree[j].weight); } HuffmanEncoding(tree); return 0; }
标签:char its 哈夫曼 class printf highlight encoding amp parent
原文地址:https://www.cnblogs.com/zili/p/9906020.html