|
常用链接
留言簿(27)
随笔分类(128)
随笔档案(169)
文章分类
文章档案(3)
others
something special
经典的c/c++
搜索
积分与排名
最新评论
阅读排行榜
评论排行榜
Powered by: 博客园
模板提供:沪江博客
|
|
|
|
|
发新文章 |
|
|
Huffman编码STL版
#include <iostream> #include <algorithm> #include <vector> #include <functional> using namespace std;
struct TreeNode ...{ double Weight;//权值 char flag;//代表符号如a,b,c,如果为非叶子节点flag=='-' struct TreeNode* left; //左子树 struct TreeNode* right;//右子树 };
/**////全局变量///vector<char> g_Path; //路径栈 vector<TreeNode> g_Heap; //用于构造树的堆 /**//////////////
bool UDGreater(TreeNode &a,TreeNode &b) ...{ //为TreeNode定义一种比较大小的函数,以便后面构造小根堆 if(a.Weight>b.Weight)...{ return true; } else...{ return false; } }
void printPath() ...{//打印从根节点到当前叶子节点的路径,即huffman编码 vector<char>::iterator it; for(it=g_Path.begin();it!=g_Path.end();it++)...{ cout<<*it; } }
void CreateHuffmanTree() ...{//构造Huffman树 TreeNode *left,*right,parent; make_heap(g_Heap.begin(),g_Heap.end(),UDGreater);//构造小根堆 while(g_Heap.size()>1)...{ left=new TreeNode(); right=new TreeNode(); pop_heap(g_Heap.begin(),g_Heap.end(),UDGreater); *left=g_Heap.back(); //取出最小的节点 g_Heap.pop_back();
pop_heap(g_Heap.begin(),g_Heap.end(),UDGreater); *right=g_Heap.back(); //取出第二小的节点 g_Heap.pop_back(); parent.left=left; //根据这两个节点生成一个新的节点 parent.right=right; parent.Weight=left->Weight+right->Weight; parent.flag='-';
g_Heap.push_back(parent); push_heap(g_Heap.begin(),g_Heap.end(),UDGreater);//在堆中添加进去新生成的节点 } }
void TravelHuffmanTree(TreeNode parent) ...{//遍历huffman树,在此过程中输出叶节点的编码 if(parent.left==NULL && parent.right==NULL)...{//如果是叶子节点 cout<<parent.flag<<":"; printPath(); //打印路径即huffman编码 cout<<endl; } else...{ g_Path.push_back('0'); TravelHuffmanTree(*parent.left); //遍历左子树 g_Path.pop_back(); g_Path.push_back('1'); TravelHuffmanTree(*parent.right); //遍历右子树 g_Path.pop_back(); } }
int main()...{ int count=0; TreeNode temp; cout<<"请输入字符的个数"<<endl; cin>>count; cout<<"请输入要编码的字符和它的权值,用空格隔开,如:a 12.5"<<endl; while(count--)...{ cin>>temp.flag>>temp.Weight; temp.left=NULL; temp.right=NULL; g_Heap.push_back(temp); } CreateHuffmanTree(); //创建huffman树 TreeNode root=g_Heap.front(); TravelHuffmanTree(root); //遍历huffman树 }
|
|