...哈夫曼树(电文的编码和译码)哈夫曼编码译码器

编辑: admin           2017-23-02         

    #include

    #include

    int n;

    int m=2*n-1;

    struct tree

    {

    float weight;

    int parent;

    int lch,rch;

    };

    struct codetype

    {

    int bits[100];

    int start;

    char ch;

    };

    tree hftree[100];

    codetype code[99];

    void creathuffmantree(int n,int m)

    {

    int i,j ,p1,p2;

    float s1,s2;

    for(i=1;i<=m;i++)

    {hftree[i].parent=0;

    hftree[i].lch=0;

    hftree[i].rch=0;

    hftree[i].weight=0;

    }

    cout<<"请输入"<

    for(i=1;i<=n;i++)

    cin>>hftree[i].weight;

    for(i=n+1;i<=m;i++)

    { p1=p2=0;

    s1=s2=32767;

    for(j=1;j<=i-1;j++)

    if (hftree[j].parent==0)

    if (hftree[j].weight

    {s2=s1;s1=hftree[j].weight;

    p2=p1;p1=j;

    }

    else

    if (hftree[j].weight

    {s2=hftree[j].weight;p2=j;

    }

    hftree[p1].parent=i;

    hftree[p2].parent=i;

    hftree[i].lch=p1;

    hftree[i].rch=p2;

    hftree[i].weight=hftree[p1].weight+hftree[p2].weight;

    }

    }

    void huffcode(int n,int m)

    {

    codetype cd;

    int c,p;

    for(int i=1;i<=n;i++)

    {

    cd.start=n+1;

    cd.ch=96+i;

    c=i;

    p=hftree[i].parent;

    while(p!=0)

    { cd.start--;

    if(hftree[p].lch==c) cd.bits[cd.start]=0;

    else cd.bits[cd.start]=1;

    c=p;

    p=hftree[p].parent;

    }

    code[i]=cd;

    }

    for(i=1;i<=n;i++)

    { cout<<"字符"<

    for(int j=code[i].start;j<=n;j++)

    cout<

    cout<

    }

    }

    void trancode(int n,int m)

    {

    int i=m;char b;

    cout<<"请输入一串二进制编码(0,1以外的数结束)";

    cin>>b;

    while ((b=='0')||(b=='1'))

    { if (b=='0') i=hftree[i].lch;

    else i=hftree[i].rch;

    if (hftree[i].lch==0)

    { cout<

    i=m;

    }

    cin>>b;

    }

    }

    void main()

    {

    cout<<"请输入权值:";

    cin>>n;

    creathuffmantree(int (n),int (m));

    huffcode(int (n),int (m));

    trancode(int (n),int (m));

    }

  •   4
  • 相关文章

    专利代理人资格考试
    初级经济师考试
    执业医师考试
    教师资格证考试
    同等学力申硕考试
    AP考试
    CCIE考试
    营养师考试
    bec考试
    gre
Copyright ©2009-2021 逆火网训All Rights Reserved.     滇ICP备2023009294号-57