使用优先队列实现哈夫曼树编码

#include 
using namespace std;
#define maxn 1025
typedef struct haffmantree {
	unsigned int weight;
	int xh;
	struct haffmantree *lchild, *rchild;
}*htree;
struct cmp
{
	bool operator() (htree f1, htree f2) // 重载括号
	{
		return (*f1).weight > (*f2).weight; // 等同于less
	}
};
int ans[maxn][maxn];
int code[maxn];
void getans(htree a, int deep) {
	haffmantree b = *a;
	if (b.lchild == NULL && b.rchild == NULL) {
		int x = b.xh;
		for (int i = 0; i < deep; i++) {
			ans[x][i] = code[i];
		}
		ans[x][maxn - 1] = deep;
		return;
	}
	code[deep] = 0;
	getans(b.lchild, deep + 1);
	code[deep] = 1;
	getans(b.rchild, deep + 1);
}
int main() {
	for (int i = 0; i < maxn; i++)code[i] = 1;
	priority_queue<htree, vector<htree>, cmp> q;
	int n;
	cin >> n;
	for (int i = 0; i < n; i++) {
		htree t = NULL;
		t = (htree)malloc(sizeof(haffmantree));
		cin >> (*t).weight;
		(*t).lchild = (*t).rchild = NULL;
		(*t).xh = i;
		q.push(t);
	}

	for (int i = 1; i < n; i++) {
		htree a = NULL;
		a = (htree)malloc(sizeof(haffmantree));
		(*a).xh = -1;
		(*a).lchild = q.top(); q.pop();
		(*a).rchild = q.top(); q.pop();
		(*a).weight = (*(*a).lchild).weight + (*(*a).rchild).weight;
		q.push(a);
	}
	getans(q.top(), 0);
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < ans[i][maxn - 1]; j++) {
			cout << ans[i][j];
		}
		cout << endl;
	}
	return 0;
}

你可能感兴趣的:(数据结构笔记)