1. 程式人生 > >每日一題之 哈夫曼編碼

每日一題之 哈夫曼編碼

描述:

給一個字串,如 abbcccddd 輸出各個字元的哈夫曼編碼

input: abbcccdddd

output : a 0 b 10 c 110 d 111

思路

哈夫曼編碼模板題

#include <bits/stdc++.h>

using namespace std;

const int maxn = 1e3+5;

struct huffman_node
{
	char c;
	int weight;
	char code[maxn];
	huffman_node* left;
	huffman_node* right;
	huffman_node(char cc, int v):c(cc),weight(v),left(nullptr),right(nullptr){}
	huffman_node(){}

};


struct cmp{
    //weight小的優先
	bool operator()(huffman_node* x,huffman_node* y){  //自定義優先順序 過載()
		return x->weight > y->weight; //表示weight小的優先
	}
};

void huffmanTreeCreat(huffman_node* &root, map<char,int>&word)
{

	priority_queue<huffman_node*,vector<huffman_node*>,cmp> treeNode;
	//
	//priority_queue<node,vector<node>,cmp>

	map<char,int>::iterator it;
	for (it = word.begin(); it != word.end(); ++it) {
		huffman_node* node = new huffman_node(it->first,it->second);
		treeNode.push(node);
	}

	//開始從葉節點構建Huffman樹

	//cout << treeNode.top()->c << " "<< treeNode.top()->weight<< endl;

	while(!treeNode.empty()) {

		//只有一個根節點
		if (treeNode.size() == 1) {
			auto node1 = treeNode.top();
			treeNode.pop();
			root = node1;
		}
		else {
			auto node1 = treeNode.top();
			treeNode.pop();
			auto node2 = treeNode.top();
			treeNode.pop();
			huffman_node* newNode  = new huffman_node;
			newNode->weight = node1->weight + node2->weight;
			if (node1->weight <= node2->weight) {  //小的權重在左邊 大的在有邊 左0右1
				newNode->left = node1;
				newNode->right = node2;
			}
			else {
				newNode->left = node2;
				newNode->right = node1;
			}

			treeNode.push(newNode);
		}


	}


}


void getHuffmanCode(huffman_node* &root)  //層次遍歷實現
{
	if (root == nullptr) return;

	huffman_node* p = root;
	queue<huffman_node*> q;
	q.push(p);
	while(!q.empty()) {
		p = q.front();
		q.pop();
		if (p->left != nullptr) {
			q.push(p->left);
			strcpy((p->left)->code,p->code);  //拷貝上級的編碼
			char* ptr = (p->left)->code;
			while(*ptr != '\0') ++ptr;
			*ptr = '0';
		}

		if (p->right != nullptr) {
			q.push(p->right);
			strcpy((p->right)->code,p->code);
			char* ptr = (p->right)->code;
			while(*ptr != '\0') ++ptr;
			*ptr = '1';
		}
	}

}

void print(huffman_node*  root) 
{
	if (root == nullptr) return;
	print(root->left);
	if (root->left == nullptr && root->right == nullptr) {
		cout << root->c << " " << root->code << endl;
	} 
	print(root->right);
}




void solve(string s) 
{
	map<char,int>word;
	int len = s.length();
	for (int i = 0; i < len; ++i) {
		if (word.find(s[i]) == word.end()) 
			word[s[i]] = 1;
		else
			word[s[i]]++;
	}


	huffman_node* root = nullptr;
	root = new huffman_node;
	huffmanTreeCreat(root,word);
	getHuffmanCode(root);
	print(root);

}

int main()
{
	string s = "abbcccdddd";
	//cin >> s;
	solve(s);

	return 0;
}