【SSL 1409】【哈夫曼树】哈夫曼树(三)

【树】哈夫曼树三

SSL 1409 【树】哈夫曼树(三)
1408 【树】哈夫曼树(二) 题解
1407 【树】哈夫曼树(一) 题解


题目

Description
根据传送的一串字符出现的频率,设置其相应的哈夫曼编码

Input
一串字符

Output
哈夫曼编码(按照中序遍历输出各个字母和编码,中间用冒号分开)

Sample Input

XINNNMM

Sample Output

N:0
M:10
X:110
I:111

解题思路

依旧是套用模板
哈夫曼树是让频率高的离根近,频率低的离根远,这样建成的树带权路径值才最小
注意这题中(我不知道其他题是不是),值相同时新加入的放在左边,先出现的放在左边(程序中用id来实现)


Code

#include <iostream>
#include <cstdio>
#include <string>
#include <map>

using namespace std;

struct DT{
	int data, l, r, addr, id;
	string c;
}a[200], f[200];
int n, fin[30];
string s;

void selectsort(int x) {
	for(int i = 1; i < x; i ++)
		for(int j = i + 1; j <= x; j ++)
			if(a[i].data > a[j].data || (a[i].data == a[j].data && a[i].id > a[j].id))
				swap(a[i], a[j]);
}

void print(int x, string s, int d) {
	if(f[x].addr == -1) {
		cout << f[x].c << ":" << s << endl;
		return;
	}
	print(f[x].l, s + '0', d + 1), print(f[x].r, s + '1', d + 1);
}

int main() {
	cin >> s; int len = s.size();
	for(int i = 0; i < len; i ++) {
		int c = s[i] - 'A';
		if(!fin[c]) fin[c] = ++ n, a[fin[c]].c = s[i], a[fin[c]].id = n;
		a[fin[c]].data ++;
	}
	for(int i = 1; i <= n; i ++)
		f[i].data = a[i].data, a[i].addr = i, f[i].c = a[i].c, f[i].addr = -1;
	int t = n + 1;
	for(int i = n; i > 1; i --, t ++) {
		selectsort(i);
		f[t] = (DT){ a[1].data + a[2].data, a[1].addr, a[2].addr, 0, t};
		a[1].data = f[t].data, a[1].addr = t, a[1].id = f[t].id;
		a[2].data = a[i].data, a[2].addr = a[i].addr, a[2].id = a[i].id;
	}
	print(t - 1, "", 0);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值