2016/11/10 1004. Huffman Coding V1

原理简单,但实现起来挺复杂的。
// Problem#: 19625
// Submission#: 4906423
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
// Problem#: 19625
// Submission#: 4906106
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include 
#include 
#include 


#define MAX  27
#define MAX_INT  99999


//哈夫曼树和哈夫曼编码的存储表示
typedef struct
{
    int weight;
    int parent,lchild,rchild;
} HTNode,*HuffmanTree; // 动态分配数组存储哈夫曼树


typedef char **HuffmanCode;


typedef struct Charnode
{
    char c;
    int weight;
}CharNode,*CharNodePtr;//不要定义为Char


CharNode *b;


int Chat_get()
{
    char c;
    int j=0;
    int m;
    int i;
    scanf("%d",&m);
    getchar();
    b=(CharNodePtr)malloc(sizeof(CharNode)*MAX);
    int a[MAX];
    for(i=0;i0),构造哈夫曼树HT,并求出n个字符的哈夫曼编码HC
void HuffmanCoding(HuffmanTree &HT,HuffmanCode &HC,int *w,int n)
{
    int m,i,s1,s2;


    HuffmanTree p;


    if(n<=1)   exit(0);
    m=2*n-1;
    HT=(HuffmanTree)malloc((m+1)*sizeof(HTNode)); // 0号单元未用
//因为0号单元未用,处理数据时候从1号单元开始
    for(p=HT+1,i=1; i<=n; ++i,++p,++w)
    {
        (*p).weight=*w;
        (*p).parent=0;
        (*p).lchild=0;
        (*p).rchild=0;
    }
    for(; i<=m; ++i,++p)  (*p).parent=0;
    // 在HT[1~i-1]中选择parent为0且weight最小的两个结点,其序号分别为s1和s2
    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;
    }
    //顺序输出哈夫曼树
    PrintHuffmanTree(HT, HC, n);
}




void sort_b(int k)
{
    int n;
    char c;
    int i,j;
    for(i=0;i=i;j--)
        {
            if(b[j].weight>b[j-1].weight)
            {
                n=b[j].weight; b[j].weight=b[j-1].weight;b[j-1].weight=n;
                c=b[j].c; b[j].c=b[j-1].c; b[j-1].c=c;
            }
        }
    }
}


int main()
{
    int k;
    int j;
    int i;
    HuffmanTree HT;
    HuffmanCode HC;
    k=Chat_get();
    int *w;
    w=(int *)malloc(sizeof(int)*k);
    sort_b(k);
    for(i=0;i

你可能感兴趣的:(Sicily快乐之旅)