霍夫曼编码解码

/**/
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <stack>
#include <queue>

typedef long long LL;
using namespace std;

int n, N;
string s[1005];

struct node
{
	int id;
	int w;
	node *l, *r;
	bool operator <(const node &x) const{
		return w == x.w ? id > x.id : w > x.w;
	}
}a[1005];

priority_queue<node> q;

void dfs(node *t, int flag, string str){
	if(t == NULL) return ;
	if(flag == 1){
		str += '1';
		s[t->id] = str;
	}else if(flag == 0){
		str += '0';
		s[t->id] = str;
	}
	if(t->l != NULL){
		dfs(t->l, 0, str);
	}
	if(t->r != NULL){
		dfs(t->r, 1, str);
	}
}

int main()
{
	//freopen("in.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);

	scanf("%d", &n);
	N = n;
	for (int i = 1; i <= n; i++){
		scanf("%d", &a[i].w);
		a[i].id = i;
		a[i].l = NULL, a[i].r = NULL;
		q.push(a[i]);
	}
	node b[1005], t1[1005], t2[1005];
	int cnt = 0;
	while(q.size() != 1){
		t1[cnt] = q.top();
		q.pop();
		t2[cnt] = q.top();
		q.pop();
		b[cnt].w = t1[cnt].w + t2[cnt].w;
		b[cnt].id = ++n;
		b[cnt].l = &t1[cnt], b[cnt].r = &t2[cnt];
		q.push(b[cnt++]);
	}
	node t = q.top();
	dfs(&t, -1, "");
	for (int i = 1; i <= N; i++){
		cout << (char)(i + 'A' - 1) << " " << s[i] << endl;
	}

	return 0;
}
/**/
/*
10
19 18 16 14 12 8 6 4 2 1
*/

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
霍夫曼编码是一种常见的数据压缩方法,用于将原始数据转换为更紧凑的编码形式。MATLAB提供了一些内置函数,可以用于实现霍夫曼编码解码。 首先,我们需要使用MATLAB中的`huffmandict`函数生成霍夫曼编码字典。该函数需要一个符号集合和对应的概率分布作为输入。符号集合可以是一组字符或数字,概率分布表示每个符号出现的概率。该函数将返回一个霍夫曼编码字典,其中包含每个符号对应的二进制编码。 接下来,我们可以使用`huffmanenco`函数将原始数据编码为相应的霍夫曼编码。该函数需要输入一个符号集合和对应的编码字典。它将返回一个编码向量,其中包含了原始数据的压缩表示。 最后,我们可以使用`huffmandeco`函数对编码数据进行解码。该函数需要输入压缩数据和对应的编码字典。它将返回一个解码向量,其中包含原始数据的恢复结果。 需要注意的是,编码和解码过程中所使用的编码字典必须是相同的,否则将无法正确解码。 以下是一个简单的示例代码: ```matlab % 创建符号集合和概率分布 symbols = {'A','B','C','D','E'}; probabilities = [0.2, 0.1, 0.4, 0.15, 0.15]; % 生成编码字典 dict = huffmandict(symbols, probabilities); % 原始数据 data = {'C', 'D', 'A', 'B', 'E', 'A'}; % 编码数据 encodedData = huffmanenco(data, dict); % 解码数据 decodedData = huffmandeco(encodedData, dict); % 输出结果 disp(decodedData); ``` 以上代码演示了如何使用MATLAB进行霍夫曼编码解码。请注意,这只是基本的示例,实际应用中可能需要根据需要进行相应的修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值