資源簡介
n元哈夫曼編碼,如果大家作為信息論課設的話,記得拿到代碼讀懂后再修改。
代碼片段和文件信息
#include
#include
#include
#include
#define?maxnum?10??//限制最多進行10元編碼?
#define?leaf?257???//最多需要編碼的字符
#define?node?2*leaf-1??//Huffman樹的結點數
#define?max?32768
using?namespace?std;
int?num;//字符串總長度
int?num1;//擴展后總數
//編碼結點
?typedef?struct{
????int?len;
????char?ch;
????char?bits[10];
}HC;
typedef?HC?HuffmanCode[leaf+1];
//huffman樹的結點
typedef?struct{
????int?weight;
????int?parent;
????int?child[maxnum];
}HTNode;
typedef?HTNode?HuffmanTree[node+1];
//統計輸入的字符串的字符以及每個字符的個數
void?jsq(string?sint?cnt[]char?str[])
{
????int?i=0j=0k=0;
//初始化
for(i=0;i<257;i++){
????????str[i]=‘\0‘;
}
????for(i=0;i<257;i++){
????????cnt[i]=0;
????}
????int?temp[257];
????for(i=0;i<257;i++)
????????temp[i]=0;
????for(i=0;s[i]!=‘\0‘;i++)
????????temp[?s[i]?]++;
????for(i=0j=0;i<=256;i++)
????????if(temp[i]!=0){
????????????j++;
????????????str[j]=i;
????????????cnt[j]=temp[i];
????????}
????num=j;
????cout<<“共有“< }
//從中挑選n個最小的出來n表示挑選多少個
void?select(HuffmanTree?HTint?lenint?n){
????int?ijmintemp;
????for(j=0;j ????????min=max;
????????for(i=1;i<=len;i++){
????????????if(HT[i].parent==0?&&?HT[i].weight ????????????????min=HT[i].weight;
????????????????temp=i;
????????????}
????????}
????????HT[temp].parent=len+1;
????????HT[len+1].child[j]=temp;????
HT[len+1].weight=HT[len+1].weight+HT[temp].weight;
????}????????????????????????????????????????????????????????????????????????????????????????????????????????????????
}
//創建霍夫曼樹
void?chuffmantree(HuffmanCode?HCHuffmanTree?HTchar?str[]int?cnt[]int?n?){
????int?ij;
????for(i=0;i<2*num-1;i++){
????????HT[i].weight=0;
????????HT[i].parent=0;
????????for(j=0;j ????????????HT[i].child[j]=0;
}
????}
for(i=1;i<=num;i++){
????????HC[i].ch=str[i];
????}
????for(i=1;i<=num;i++){
????????HT[i].weight=cnt[i];//每個結點權值等于相應的符號個數值
????}
????//擴充
????int?k=0;
????if(num!=n)
k=(num-n)/(n-1)+1;
????num1=(n-1)*k+n;
for(i=num;i HT[i].weight=0;
}
????for(i=num1+1;i<=num1+k+1;i++){
????????//從中挑選n個最小的出來
????????select(HTi-1n);
????}
}
/
- 上一篇:python wordcloud whl包
- 下一篇:畫線算法C++的實現-鼠標交互
評論
共有 條評論