用C++实现哈夫曼编码

@用C++实现哈夫曼编码
哈夫曼编码

霍夫曼编码使用变长编码表对源符号(如文件中的一个字母)进行编码,其中变长编码表是通过一种评估来源符号出现机率的方法得到的,出现机率高的字母使用较短的编码,反之出现机率低的则使用较长的编码,这便使编码之后的字符串的平均长度、期望值降低,从而达到无损压缩数据的目的。

问题描述

给定报文中26个字母a-z及空格的出现频率{64, 13, 22, 32, 103, 21, 15, 47, 57, 1, 5, 32, 20, 57, 63, 15, 1, 48, 51, 80, 23, 8, 18, 1, 16, 1, 168},构建哈夫曼树并为这27个字符编制哈夫曼编码,并输出。模拟发送端,从键盘输入字符串,以%为结束标记,在屏幕上输出输入串的编码;模拟接收端,从键盘上输入0-1哈夫曼编码串,翻译出对应的原文。

代码实现

// An highlighted block
var foo = 'bar';
#include<bits/stdc++.h>
using namespace std;
typedef struct HTNode
{
    int weight;
    int parent,lchild,rchild;
} HTNode, *HuffmanTree;

typedef char **HuffmanCode;
int i,j,m,n,s1,s2,w[100];
void select(HuffmanTree HT,int n, int &s1, int &s2)
{
    for(i=1; i<=n; i++)
    {
        if(HT[i].parent==0)
        {
            s1=i;
            break;
        }
    }
    for(i=1; i<=n; i++)
    {
        if(HT[i].parent==0 && HT[s1].weight>HT[i].weight)
        {
            s1=i;
        }
    }
    for(i=1; i<=n; i++)
    {
        if(HT[i].parent==0 && i!=s1)
        {
            s2=i;
            break;
        }
    }
    for(i=1; i<=n; i++)
    {
        if(HT[i].parent==0 && HT[s2].weight>HT[i].weight && i!=s1)
        {
            s2=i;
        }
    }
}

void createhuffmantree(HuffmanTree &HT,int n)
{
    if(n<=1)
    {
        return;
    }
    m=(2*n)-1;
    HT=new HTNode[m+1];
    for(i=1; i<=m; i++)
    {
        HT[i].parent=0;
        HT[i].lchild=0;
        HT[i].rchild=0;
    }
    for(i=1; i<=n; i++)
    {
        cin>>HT[i].weight;
    }
    for(i=n+1; i<=m; i++)
    {
        select(HT,i-1,s1,s2);
        HT[s1].parent=i;
        HT[s2].parent=i;
        HT[i].lchild=s1;
        HT[i].rchild=s2;
        HT[i].weight=HT[s1].weight+HT[s2].weight;
    }
}
void creathuffmancode(HuffmanTree HT,HuffmanCode &HC,int n)
{
    int start,c;
    int f;
    HC=new char*[n+1];
    char *cd=new char[n];
    cd[n-1]='\0';
    for(i=1; i<=n; i++)
    {
        start=n-1;
        c=i;
        f=HT[c].parent;
        while(f!=0)
        {
            start--;
            if(HT[f].lchild==c)
            {
                cd[start]='0';
            }
            else
            {
                cd[start]='1';
            }
            c=f;
            f=HT[f].parent;
        }
        HC[i]=new char[n-start];
        strcpy(HC[i],&cd[start]);
    }
    delete cd;
}

void TranCode(HuffmanTree HT,char a[],char zf[],char b[],int n)
{
    int q=2*n-1;
    int k=0;
    for(i=0; a[i]!='\0'; i++)
    {
        if(a[i]=='0')
        {
            q=HT[q].lchild;
        }
        else if(a[i]=='1')
        {
            q=HT[q].rchild;
        }
        if(HT[q].lchild==0 && HT[1].rchild==0)
        {
            b[k++]=zf[q];
            q=2*n-1;
        }
    }
    b[k]='\0';
}
void show_help()
{
    cout<<"********************************************************************"<<endl;
    cout<<"********* 1.输入HuffmanTree的参数.                        **********"<<endl;
    cout<<"********* 2.初始化HuffmanTree参数(含有26字母及空格).      **********"<<endl;
    cout<<"********* 3.创建HuffmanTree和编码表.                      **********"<<endl;
    cout<<"********* 4.输出编码表.                                   **********"<<endl;
    cout<<"********* 5.输入编码,并翻译为字符.                       **********"<<endl;
    cout<<"********* 6.输入字符,并实现编码.                         **********"<<endl;
    cout<<"********* 7.退出.                                         **********"<<endl;
    cout<<"********************************************************************"<<endl;
}

int main()
{
    HuffmanTree HT;
    HuffmanCode HC;
    int operator_code;
    char a[100];
    char b[100];
    char c[100];
    char zf[100];
    show_help();
    while(1)
    {
        cout<<"请输入操作代码:"<<endl;
        cin>>operator_code;
        if(operator_code==1)
        {
            cout<<"请输入需要编码的字符个数:"<<endl;
            cin>>n;
        }
        else if(operator_code==2)
        {
            cout<<"请输入所有编码的字符:"<<endl;
            for(i=1; i<=n; i++)
            {
                cin>>zf[i];
            }
            cout<<"请输入每一个字符的权值:"<<endl;
            createhuffmantree(HT,n);
            cout<<"结点"<<"\t"<<"字符"<<"\t"<<"权值"<<"\t"<<"双亲"<<"\t"<<"左孩子"<<"\t"<<"右孩子"<<endl;
            for(int i=1;i<=n;i++)
            {
                cout<<i<<"\t"<<zf[i]<<"\t"<<HT[i].weight<<"\t"<<HT[i].parent<<"\t"<<HT[i].lchild<<"\t"<<HT[i].rchild<<endl;
            }
        }
        else if(operator_code==3)
        {
            creathuffmancode(HT,HC,n);
        }
        else if(operator_code==4)
        {
            cout<<"结点"<<"\t"<<"字符"<<"\t"<<"权值"<<"\t"<<"编码"<<endl;
            for(int i=1;i<=n;i++)
            {
                cout<<i<<"\t"<<zf[i]<<"\t"<< HT[i].weight<<"\t"<<HC[i]<<endl;
            }
            cout<<endl;
        }
        else if(operator_code==5)
        {
            cout<<"输入二进制编码:"<<endl;
            cin>>a;
            TranCode(HT,a,zf,b,n);
            cout<<"结果为:"<<b<<endl;

        }else if(operator_code==6)
        {
            cout<<"请输入一串字符"<<endl;
            cin>>c;
            for(i=0;i<sizeof(c)/sizeof(c[0]);i++)
            {
                for(j=1;i<=n;j++)
                {
                    if(c[i]==zf[j])
                    {
                        cout<<HC[j];
                        break;
                    }
                }
            }
            cout<<endl;
        }else if(operator_code==7)
        {
            break;
        }
    }
    return 0;
}



实现效果

在这里插入图片描述
在这里插入图片描述

  • 13
    点赞
  • 69
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
哈夫曼编码是一种前缀编码方式,在通信领域广泛应用。下面是使用 C++ 实现哈夫曼编码的基本步骤: 1. 定义一个结构体来表示哈夫曼树的节点: ```c++ struct Node { char ch; // 字符 int weight; // 权重 Node *left, *right; // 左右子树指针 }; ``` 2. 定义一个比较函数,用于建立小根堆: ```c++ struct cmp { bool operator() (Node* a, Node* b) { return a->weight > b->weight; } }; ``` 3. 定义一个函数,用于构建哈夫曼树: ```c++ Node* buildHuffmanTree(map<char, int>& mp) { priority_queue<Node*, vector<Node*>, cmp> pq; for (auto iter : mp) { Node* node = new Node; node->ch = iter.first; node->weight = iter.second; node->left = node->right = nullptr; pq.push(node); } while (pq.size() > 1) { Node* left = pq.top(); pq.pop(); Node* right = pq.top(); pq.pop(); Node* parent = new Node; parent->ch = '\0'; parent->weight = left->weight + right->weight; parent->left = left; parent->right = right; pq.push(parent); } Node* root = pq.top(); pq.pop(); return root; } ``` 4. 定义一个递归函数,用于生成哈夫曼编码: ```c++ void generateHuffmanCode(Node* root, string code, map<char, string>& huffmanCode) { if (root == nullptr) { return; } if (root->left == nullptr && root->right == nullptr) { huffmanCode[root->ch] = code; return; } generateHuffmanCode(root->left, code + "0", huffmanCode); generateHuffmanCode(root->right, code + "1", huffmanCode); } ``` 5. 定义一个函数,用于压缩字符串: ```c++ string compress(string str, map<char, string>& huffmanCode) { string compressedStr = ""; for (char ch : str) { compressedStr += huffmanCode[ch]; } return compressedStr; } ``` 6. 定义一个函数,用于解压字符串: ```c++ string decompress(string compressedStr, Node* root) { string originalStr = ""; Node* node = root; for (char ch : compressedStr) { if (ch == '0') { node = node->left; } else { node = node->right; } if (node->left == nullptr && node->right == nullptr) { originalStr += node->ch; node = root; } } return originalStr; } ``` 完整代码如下: ```c++ #include <iostream> #include <queue> #include <map> using namespace std; struct Node { char ch; int weight; Node *left, *right; }; struct cmp { bool operator() (Node* a, Node* b) { return a->weight > b->weight; } }; Node* buildHuffmanTree(map<char, int>& mp) { priority_queue<Node*, vector<Node*>, cmp> pq; for (auto iter : mp) { Node* node = new Node; node->ch = iter.first; node->weight = iter.second; node->left = node->right = nullptr; pq.push(node); } while (pq.size() > 1) { Node* left = pq.top(); pq.pop(); Node* right = pq.top(); pq.pop(); Node* parent = new Node; parent->ch = '\0'; parent->weight = left->weight + right->weight; parent->left = left; parent->right = right; pq.push(parent); } Node* root = pq.top(); pq.pop(); return root; } void generateHuffmanCode(Node* root, string code, map<char, string>& huffmanCode) { if (root == nullptr) { return; } if (root->left == nullptr && root->right == nullptr) { huffmanCode[root->ch] = code; return; } generateHuffmanCode(root->left, code + "0", huffmanCode); generateHuffmanCode(root->right, code + "1", huffmanCode); } string compress(string str, map<char, string>& huffmanCode) { string compressedStr = ""; for (char ch : str) { compressedStr += huffmanCode[ch]; } return compressedStr; } string decompress(string compressedStr, Node* root) { string originalStr = ""; Node* node = root; for (char ch : compressedStr) { if (ch == '0') { node = node->left; } else { node = node->right; } if (node->left == nullptr && node->right == nullptr) { originalStr += node->ch; node = root; } } return originalStr; } int main() { string str = "hello world"; map<char, int> mp; for (char ch : str) { mp[ch]++; } Node* root = buildHuffmanTree(mp); map<char, string> huffmanCode; generateHuffmanCode(root, "", huffmanCode); string compressedStr = compress(str, huffmanCode); cout << "Compressed string: " << compressedStr << endl; string originalStr = decompress(compressedStr, root); cout << "Original string: " << originalStr << endl; return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值