【求助】問一個關於k叉哈夫曼樹的問題


問題描述:設某系統在通信聯系中可能出現n種字符,在通信中他們出現的頻率分別為:p1,p2,...pn;如果電文中只允許出現0,1,2三種碼值,請構造這n種字符的最優不等長前綴編碼。
程序如下:
typedef struct DataType{
    char cha;
    int  fre;
    }DataType,*datatype;    
typedef struct PCCtreeNode{
    DataType data;
    struct PCCtreeNode *child,*next;
    int tag;
    }PCCtreeNode,*PCCtree;
#include "assistance.h"
#include "lk_queue.h"
#include <iostream>
using namespace std;
main()
{
    int b,n,i,j,num,no;
     cout<<"請輸入字符數量n:";
    cin>>n;
    LinkQueue<PCCtreeNode*> qa;
    PCCtreeNode *PCCtree=new PCCtreeNode,*head,*cur,*q=new PCCtreeNode,*a=new PCCtreeNode,*p=new PCCtreeNode;
    cout<<"輸入字符種類:";
    cur=head=new PCCtreeNode;
    for(i=0;i<n;i++)
    {
        cur->next=new PCCtreeNode;
        cur=cur->next;
        qa.EnQueue(cur);       
                }
    cur->next=NULL;
    cur=head->next;   
    for(i=0;i<n;i++)
    {
        cin>>cur->data.cha;
        cur=cur->next;
        } 
    cout<<"請輸入出現頻率:";
    cur=head->next;
    for(i=0;i<n;i++)
    {
        cin>>cur->data.fre;
        cur=cur->next;
        }
    for(i=0;i<n;i++)
    {
        cur=head->next;
        for(j=i;j<n-1;j++)
        {
            if(cur->data.fre>cur->next->data.fre)
            {
                DataType sp;
                sp=cur->data;
                cur->data=cur->next->data;
                cur->next->data=sp;
                }
            cur=cur->next;
        }}
    while(head->next->next!=NULL)
    {cur=head->next;
    PCCtree=new PCCtreeNode; 
    PCCtree->child=cur;
    cur->tag=1;
    cur->next->tag=2;
    cur->next->next->tag=0;    
    PCCtree->data.fre=cur->data.fre+cur->next->data.fre+cur->next->next->data.fre;
    if(cur->next->next->next==NULL)
    {head->next=PCCtree;PCCtree->next=NULL;}
    else if(cur->next->next->next!=NULL)
    {head->next=cur->next->next->next;}
    cur->next->next->next=PCCtree;
    if(PCCtree->data.fre<head->next->data.fre)
    {PCCtree->next=head->next;head->next=PCCtree;}
    else 
    {cur=head->next;
    while(cur->next!=NULL&&PCCtree->data.fre>=cur->data.fre)
    {
        q=cur;
        cur=cur->next;
        }
        if(PCCtree->data.fre>=cur->data.fre)
        {    
            cur->next=PCCtree;
            PCCtree->next=NULL;        
           }
        else if(head->next->next!=NULL){     
        q->next=PCCtree;
        PCCtree->next=cur;
        }}}
    while(!qa.Empty())
    {
        qa.DelQueue(q);
        int i=n;
        int code[n];
        cout<<q->data.cha<<"的編碼是:";
        while(q->next)
        {
            code[i]=q->tag;
            i--;
            while(q->tag)q=q->next;
            q=q->next;
            }
        for(int k=i+1;k<=n;k++)cout<<code[k];
        cout<<endl;
        } 
    system("PAUSE");  
    }

做數據測試的時候,輸入0,系統會崩潰然后自動關閉,弱弱的問一下,怎么去除n邊界值0的情況呀?

2 个解决方案

#1


對0做特殊處理
以前做個1也是特殊情況,被逼無奈只能特殊處理

#2


已經全部改好啦~謝謝啦~

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com