为了考研很久没有搞技术了,现在海大考上已经很多天了,无意看到以前考研上机做的考研真题,顺便就粘贴上来冒个泡.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std ;
class HaffumanNode
{
public:
int wight ;
char ch ;
HaffumanNode *left ;
HaffumanNode *right ;
HaffumanNode(char _ch,int _wight,HaffumanNode *_left = NULL,HaffumanNode *_right = NULL) ;
HaffumanNode(const HaffumanNode &haffuman) ;
~HaffumanNode() ;
bool isLeaf() ;
} ;
HaffumanNode::HaffumanNode(const HaffumanNode &haffuman)
{
wight = haffuman.wight ;
ch = haffuman.ch ;
left = haffuman.left ;
right = haffuman.right ;
}
HaffumanNode::HaffumanNode(char _ch,int _wight,HaffumanNode *_left,HaffumanNode *_right)
{
ch = _ch ;
wight = _wight ;
left = _left ;
right = _right ;
}
HaffumanNode::~HaffumanNode()
{
}
bool HaffumanCompare(const HaffumanNode &left,const HaffumanNode &right)
{
return (left.wight > right.wight) ;
}
bool HaffumanNode::isLeaf()
{
return (left == NULL && right == NULL) ;
}
vector<HaffumanNode> ListHaffuman ;
void GetHaffumanNodeList(string str)
{
int strLen ;
int i ;
vector<HaffumanNode>::iterator it ;
HaffumanNode *p ;
strLen = str.length() ;
for(i = 0 ; i < strLen ;i++)
{
for(it = ListHaffuman.begin() ; it != ListHaffuman.end() ; it++)
{
if(it->ch == str[i])
{
it->wight++ ;
break ;
}
}
if(it == ListHaffuman.end())
{
p = new HaffumanNode(str[i],1) ;
ListHaffuman.push_back(*p) ;
}
}
}
void ShowListHaffuman(void)
{
vector<HaffumanNode>::iterator it ;
cout<<"字符"<<'\t'<<"权重"<<endl ;
for(it = ListHaffuman.begin() ;it != ListHaffuman.end() ; it++)
{
cout<<it->ch<<'\t'<<it->wight<<endl ;
}
cout<<endl ;
}
void PrintLeafCode(HaffumanNode &tree,string bincode)
{
if(tree.left != NULL)
{
bincode += '0' ;
PrintLeafCode(*tree.left,bincode) ;
bincode = bincode.substr(0,bincode.length() - 1) ;
}
if(tree.isLeaf())
{
cout<<tree.ch<<": "<<bincode.c_str()<<endl ;
}
if(tree.right != NULL)
{
bincode += '1' ;
PrintLeafCode(*tree.right,bincode) ;
bincode = bincode.substr(0,bincode.length() - 1) ;
}
}
void CreatHaffumanTree(vector<HaffumanNode> &ListHaffuman)
{
int vecSize ;
while((vecSize = ListHaffuman.size()) > 1)
{
sort(ListHaffuman.begin(),ListHaffuman.end(),HaffumanCompare) ;
HaffumanNode *Leftnode = new HaffumanNode( ListHaffuman[vecSize - 2]) ;
HaffumanNode *Rightnode = new HaffumanNode(ListHaffuman[vecSize - 1]) ;
ListHaffuman.pop_back() ;
ListHaffuman.pop_back() ;
if(Leftnode->wight > Rightnode->wight)
{
swap(*Leftnode,*Rightnode) ;
}
HaffumanNode *father = new HaffumanNode('*',(Leftnode->wight + Rightnode->wight),Leftnode,Rightnode) ;
ListHaffuman.push_back(*father) ;
}
string bincode ;
HaffumanNode *tree = new HaffumanNode(ListHaffuman.front()) ;
PrintLeafCode(*tree,bincode) ;
}
int main()
{
char str[50] ;
gets(str) ;
GetHaffumanNodeList(str) ;
sort(ListHaffuman.begin(),ListHaffuman.end(),HaffumanCompare) ;
ShowListHaffuman() ;
cout<<endl ;
cout<<endl ;
CreatHaffumanTree(ListHaffuman) ;
return 0 ;
}