Huffman

链表实现
时间复杂度:O(n)

#include <bits/stdc++.h>
#define maxn 1005

using namespace std;
struct node* create(char *ch, int *w, int n);
void print(struct node* root, string res);
struct node {
	char data;
	int weight;
	struct node *left, *right;
};
struct cmp {
	bool operator()(node*a, node*b) {
		if (a->weight == b->weight)
			return a->data > b->data;
		return a->weight > b->weight;
	}
};
int n;
char ch[maxn];
int weight[maxn];
int main() {
	cout << "请输入字符个数: " << endl;
	cin >> n;
	cout << "请一次输入每个字符以及其出现的次数: " << endl;
	for (int i = 0; i < n; i++) {
		cin >> ch[i];
		cin >> weight[i];
	}

	struct node* root = create(ch, weight, n);
	print(root, "");

	system("pause");
	return 0;
}

struct node* create(char *ch, int *w, int n) {
	priority_queue<struct node*, vector<struct node*>, cmp >q;
	
	//初始化
	for (int i = 0; i < n; i++) {
		struct node *temp = (struct node*)malloc(sizeof(struct node));
		temp->data = *ch;
		temp->weight = *w;
		temp->left = temp->right = NULL;
		q.push(temp);
		
		ch++;
		w++;
	}
	struct node* ans = NULL;
	for(int i = 1; i<n; i++){
		struct node *a = (struct node*)malloc(sizeof(struct node));
		struct node *b = (struct node*)malloc(sizeof(struct node));
		struct node *tmp = (struct node*)malloc(sizeof(struct node));
		a = q.top();
		q.pop();
		b = q.top();
		q.pop();
		
		tmp->weight = a->weight + b->weight;
		tmp->data = NULL;
		tmp->left = a;	//最小的作为左子树
		tmp->right = b;	//第二小的作为右子树

		ans = tmp;
		q.push(tmp);
	}
	cout << ans->weight << endl;
	return ans;
}

void print(struct node* root, string res) {
	if (!root) 
		return;
	
	if (!root->left && !root->right && root->data) {
		cout << root->data << ": ";
		cout << res << endl;
	}

	print(root->left, res + "0");
	print(root->right, res + "1");
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值