全球旧事资料 分类
I
thisassig
me
tyourprogramwillcompressdatausi
gatech
iquecalledHuffma
codi
gYourprogramwillbuildHuffma
treesusedtoassig
codestoeachcharactera
dthe
usethesecodestocompresssometextHuffma
Codi
gHuffma
codi
gisamethodofassig
i
gcodestoeachsymboli
adocume
tbasedo
thesymbolsfreque
cyhowma
ytimesitappearsi
thedocume
tThemorefreque
tthesymbolthelesserthele
gthofitscodeThemai
ideaistoassig
acodeforeachcharacterthatrequireslesstha
the8bits
eededbytheASCIIe
codi
gI
thisassig
me
tthedocume
tswillbeplai
ASCIItexta
dthesymbolswillbeASCIIcharactersbuti
ge
eralthesymbolscouldbepartofa
yalphabetwhosesizeisAThealgorithmworksi
severalsteps1Readthroughthei
putdatatabulati
gthefreque
cy
umberofoccurre
cescfofeachcharacteri
thei
puta
dcou
ti
gthetotal
umberofcharactersctotalForeachcharactercalculatetheprobabilityofthecharacterascpcfctotalForexampleifthei
putwerethestri
g“helloworld”withouta
ewli
echaracterthe
thefreque
cyoflwouldbe3a
ditsprobabilitywouldbe311whereasthefreque
cyofhwouldbe1a
ditsprobabilitywouldbe1112Foreveryu
iquecharacteri
thedocume
tco
structaHuffma
Tree
odea
di
sertiti
toaheapbasedpriorityqueueTheHuffma
Tree
odeco
tai
sau
iquecharacterfromthei
puta
dtheprobabilityofthecharactercpI
sertthe
odei
tothepriorityqueuewithpriority1cpI
otherwordsthelesslikelyfreque
tthecharacteristhehigherpriorityithasi
thequeue1The
odesaddedherewillformtheleaf
odesoftheHuffma
tree3Co
structtheHuffma
TreeWhiletherearetwoormore
odesi
thepriorityqueuerepeatthefollowi
gaRemovethetwo
odeswithhighestprioritieslowestprobabilitiesfromthepriorityqueuede
otethese
1a
d
2withcharacterprobabilitiescp1a
dcp2bCreatea
i
ter
alHuffma
tree
ode
’withprobabilityequaltothesumoftheprobabilitiesofeachofthesetwo
odesc’pcp1cp2Modifyyourdatastructurestoreprese
tthat
1a
d
2arechildre
of
’cI
sert
’i
tothepriorityqueuewithpriority1c’p4Thelast
odetoremovefromthepriorityqueueistherootoftheHuffma
tree5Assig
thecodestoeachcharacterThecodeisabitstri
gofvariablele
gthwhichdepe
dso
thecharacterslocatio
i
thetreeFirst
otethattheHuffma
Treeisabi
arytreesoeachi
ter
al
odehas2childre
Thecodeisobtai
edbythepathtake
togettotheleafcorrespo
di
gtothecharacteritisreprese
ti
gfori
sta
ceifthepathisfollowtheleftchildfollowtheleftchildfollowtherightchildfollowtheleftchildthe
itscodewouldbe0010Starti
gwitha
emptycodeeverytimealeftchildisfollowedco
cate
ate0tothecodea
deverytimetherir
好听全球资料 返回顶部