欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C++實(shí)現(xiàn)哈夫曼編碼

 更新時(shí)間:2020年04月28日 08:56:11   作者:南小唄  
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)哈夫曼編碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了C++實(shí)現(xiàn)哈夫曼編碼的具體代碼,供大家參考,具體內(nèi)容如下

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;

int Max = 300;

class tree{
 public:
 char s;
 int num;
 tree *left;
 tree *right;
 tree(){
  s= '!';
  num = 0;
  left = 0;
  right = 0;
 }
 tree(char a,int n,tree* p1,tree* p2){
  s = a;
  num = n;
  left = p1;
  right = p2;
 }
};

vector<tree *> open;

/*********************************
**中序遍歷輸出各節(jié)點(diǎn)及其哈夫曼編碼
*********************************/ 
void inorder(tree *t,string s){
 if(t != 0){
 inorder(t->left,s+'0');
 if(t->s != '!')
  cout<<t->s<<":"<<s<<endl;
 inorder(t->right,s+'1');
 }
}


int main(){
 int a[Max];
 for(int i = 0;i < Max;i++)
 a[i] = 0;  //初始化數(shù)組 
 string s;
 cout<<"請(qǐng)輸入字符串:";
 cin>>s;
 
 vector<char> v;
 vector<char>::iterator vit;
 for(int i = 0;i < s.length();i ++){
 a[s[i]]++;  //確定每個(gè)字符出現(xiàn)的次數(shù)(頻率) 
 vit = find(v.begin(),v.end(),s[i]);
 if(vit == v.end()) //相同的字符只保留一個(gè) 
  v.push_back(s[i]);
 }
 for(int i = 0;i < v.size();i ++){
 tree *n = new tree();
 n->s = v[i];
 n->num = a[v[i]];
 open.push_back(n); //存入open表中 
 }
 
 /************************
 **
 **構(gòu)造哈夫曼樹(shù) 
 **
 *************************/ 
 tree *root;
 while(open.size() != 1){
 tree *min1,*min2; //min1,min2是當(dāng)前open表中num值最小的節(jié)點(diǎn) 
 int sit1,sit2;
 min1 = open.front();
 sit1 = 0;
 for(int i = 0;i < open.size();i++){
  if(open[i]->num < min1->num){
  min1 = open[i];
  sit1 = i;
  }
 }
 open.erase(open.begin()+sit1);
 
 min2 = open.front();
 sit2 = 0;
 for(int i = 0;i < open.size();i++){
  if(open[i]->num < min2->num){
  min2 = open[i];
  sit2 = i;
  }
 }
 open.erase(open.begin()+sit2);
 
 tree *t = new tree('!',min1->num + min2->num,min1,min2); //構(gòu)造新節(jié)點(diǎn),左右指針指min1和min2 
 open.push_back(t); //存入open表中 
 root = t;
 }
 
 cout<<"它的哈夫曼編碼為:"<<endl;
 string s1 = "";
 inorder(root,s1);
 
 return 0;
}```

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論