Huffman number and Huffman coding

Source: Internet
Author: User

#include <stdio.h>#include<iostream>using namespacestd;structHuffnode//Huffman tree node structure{    intWeight//Weighted Value    intParent//parent Node    intLchild;//left son    intRchild;//Right son};structHuffcode//Huffman tree node coding structure{    intbit[Ten];//Store Huffman Code    intStart//The starting position of Huffman encoding in the array    intWeight//Weighted Value};//Implement Huffman codingvoidHuffman (intW[],intn,huffnode Hn[],huffcode hc[]) {    intm1,m2; intx1,x2;    Huffcode cd; intchild,parent; inti,j;  for(i=0; i<2*n-1; i++)//Initialize Huffman tree    {        if(i<N) hn[i].weight=W[i]; ElseHn[i].weight=0; Hn[i].parent=0; Hn[i].lchild= -1; Hn[i].rchild= -1; }     for(i=0; i<n-1; i++)//Constructing the N-1 branch node of Huffman Tree{M1= m2 = +; X1= x2 =0;  for(j=0; j<n+i; J + +)        {            if(hn[j].weight<m1&&hn[j].parent==0) {m2=M1; M1=Hn[j].weight; X2=X1; X1=J; }            Else if(hn[j].weight<m2&&hn[j].parent==0) {m2=Hn[j].weight; X2=J; }} hn[n+i].weight = hn[x1].weight+Hn[x2].weight; Hn[x1].parent= n+i; Hn[x2].parent= n+i; Hn[n+i].lchild =X1; Hn[n+i].rchild =x2; }     for(i=0; i<n; i++)//Huffman code generated by Huffman tree{cd.weight=Hn[i].weight; Cd.start= N1; Child=i; Parent=hn[i].parent;  while(parent!=0)        {            if(hn[parent].lchild==Child ) Cd.bit[cd.start]=0; Else if(hn[parent].rchild==Child ) Cd.bit[cd.start]=1; Cd.start--; Child=parent; Parent=hn[child].parent; } hc[i].weight=Cd.weight; Hc[i].start=Cd.start;  for(j=hc[i].start+1; j<n; J + +) Hc[i].bit[j]=Cd.bit[j]; }}intMainintargcChar*argv[]) {    intW[] = {4,2,6,8,3,2,1}; intn =7; Huffnode*hn =Newhuffnode[2*n-1]; Huffcode*HC =NewHuffcode[n];    Huffman (W,N,HN,HC); cout<<"Huffman code is as follows:"<<Endl;  for(intI=0; i<n; i++) {cout<<"weight="<"    "<<"code=";  for(intj=hc[i].start+1; j<n; J + +) cout<<Hc[i].bit[j]; cout<<Endl; }    return 0;}

Huffman number and Huffman coding

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.