赫夫曼編碼(輸入字串轉化為赫夫曼編碼)

2021-10-21 02:25:48 字數 2949 閱讀 5223

哈夫曼編碼(huffman coding),又稱霍夫曼編碼,是一種編碼方式,哈夫曼編碼是可變字長編碼(vlc)的一種。huffman於2023年提出一種編碼方法,該方法完全依據字元出現概率來構造異字頭的平均長度最短的碼字,有時稱之為最佳編碼,一般就叫做huffman編碼(有時也稱為霍夫曼編碼)。

#**

#include

#include

#include

#include

#include

using

namespace std;

typedef

struct huffman_node

huffman_node;

void

defineweight

(vector<

char

>v, vector<

int>

&hash)

for(

unsigned

int i =

0; i

size()

; i++)}

void

select_tow_min

(vector

&huffmantree,

int&first_min,

int&second_min,

int n)

} min_value = int_max;

for(

int i=

0; i

if(first_min > second_min)

}void

huffman_solve

(vector

&huffmantree,

vector

&code, vector<

int>

&hash, vector<

char

> v)}if

( hashsize <=1)

huffmantree.

resize

(hashsize*2-

1);for

(int k=

0, i =

0; k

size()

; k++

)while

(j !=-1

&& v[k]

!= v[j])if

(j ==-1

)}for(

int i=hashsize; i

1; i++

)for

(int i=hashsize; i

1; i++

)//求出字首碼

int child, parent;

for(

int i=

0; i

size()

; i++

)else

child = parent;

parent = huffmantree[child]

.parent;

}while

(parent !=0)

;reverse

(str.

begin()

,str.

end())

; code.

push_back

(str)

; child = i+1;

parent = huffmantree[child]

.parent;

continue;}

while

(j !=-1

&& v[i]

!= v[j])if

(j ==-1

)else

child = parent;

parent = huffmantree[child]

.parent;

}while

(parent !=0)

;reverse

(str.

begin()

,str.

end())

; code.

push_back

(str)

; child = i+1;

parent = huffmantree[child]

.parent;

}else

else

child = parent;

parent = huffmantree[child]

.parent;

}while

(parent !=0)

;reverse

(str.

begin()

,str.

end())

; code.

push_back

(str)

; child = i;

parent = huffmantree[child]

.parent;}}

}int

main()

v.pop_back()

; vector<

int> hash;

defineweight

(v, hash)

; vector huffmantree;

//哈夫曼樹

vector code;

//赫夫曼編碼

huffman_solve

(huffmantree, code, hash, v)

;for

(vector

::iterator it=code.

begin()

; it!=code.

end(

); it++

)system

("pause");

return0;

}

#執行結果

字串轉化為陣列,陣列轉化為字串。

做題中常遇到字串轉化為數字,數字轉化為字串等,自己轉化比較麻煩,c語言提供了幾個標準庫函式,可以將任意型別 整型 長整型 浮點型等 的數字轉換為字串。1.整數轉化為字串。itoa include include int main itoa 函式有3個引數 第乙個引數是要轉換的數字,第二個引數是要寫入...

整數轉化為字串和字串轉化為整數

整數轉化為字串 includeint main temp i 0 為什麼等於0就可以,因為將temp定義為字串陣列後,等號右邊的數相當於ascii碼值,0就相當於 0 如果寫為61,輸出就為 12345 printf s temp i i 1 while i 0 str j temp i str j...

字串轉化為數值

工作時遇到這樣的乙個情況 伺服器a向b傳送請求並接受結果,耗時300ms,伺服器b從接受請求到傳送完畢,耗時100ms。由於是內網,不可能有200ms的網路延遲。後經檢測,是因為傳輸時用的是字串格式,解析時用了sscanf造成的。由於sscanf要考慮到變參問題,並且接受的種類更加豐富 相對於str...