算法作业——Huffman编码

#include <bits/stdc++.h>

using namespace std;

const int maxn = 1e4 + 10;

map<string, string> code;    

// Huffman 数的结点
struct Node 
{
    int key;   // 权值
    string c;    // 哪个字符
    Node* lchild;
    Node* rchild;
    Node(int key, string c) : key(key), c(c), lchild(NULL), rchild(NULL) {}
};

int frequency[maxn];  // 每种字符的频率

Node* ptr;

deque<Node*> forest;        // 森林

void printCode(deque<bool> ptr);          

bool compare( Node *a, Node *b) {
    return a->key < b->key;
}

void get_code(Node* u, string cd)
{
    if(!u->lchild && !u->rchild) {
        code[u->c] = cd;
        return ;
    }
    else {
        get_code(u->lchild, cd + "0");
        get_code(u->rchild, cd + "1");
    }
}
int main() {
    freopen("i.txt", "r", stdin);
    int n;
    cin >> n;                   //  输入字符的数量 
    for (int i = 0; i < n; i++) {
        string c;
        cin >> frequency[i] >> c;                // 輸入10個權值
        ptr = new Node(frequency[i], c);
        ptr->key = frequency[i];
        ptr->lchild = NULL;
        ptr->rchild = NULL;
        forest.push_back(ptr);
    } 
    for (int i = 0; i < n - 1; i++) {
        sort(forest.begin(), forest.end(), compare);
        ptr = new Node(0, "");
        ptr->key = forest[0]->key + forest[1]->key;
        ptr->lchild = forest[0];
        ptr->rchild = forest[1];
        forest.pop_front();
        forest.pop_front();
        forest.push_back(ptr);
    }
    ptr = forest.front();
    get_code(ptr, "");
    for(auto & it : code) {
        cout << it.first << ": " << it.second << endl;
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值