问题描述
根据传送的一串字符出现的频率,设置其相应的哈夫曼编码。
样例输入
XINNNMM
样例输出
N:0
M:10
X:110
I:111
算法讨论
统计字符串每个字母的频率,构建哈弗曼树,注意当两权值相同时不按字典序排序,按在字符串中出现的顺序排序,最好将对应字母存储起来,不然输出很麻烦,还有可能会错。
const
maxn=200;
var
a:array[0..maxn,1..2] of longint;
f:array[0..maxn,1..3] of longint;
v:array[0..maxn] of longint;
d,d1:array[0..maxn] of char;
c:array['A'..'Z'] of longint;
f1:array['A'..'Z'] of boolean;
i,j,n,t:longint;
flag:boolean;
st:string;
o:char;
procedure sort(k:longint);
var
i,j,t:longint;
x:char;
begin
for i:=1 to k-1 do
for j:=i+1 to k do
if (a[i,1]>a[j,1]) or ((a[i,1]=a[j,1]) and (a[i,2]>a[j,2]))
then begin
t:=a[i,1]; a[i,1]:=a[j,1]; a[j,1]:=t;
t:=a[i,2]; a[i,2]:=a[j,2]; a[j,2]:=t;
x:=d[i]; d[i]:=d[j]; d[j]:=x
end;
end;
procedure vist(t:longint);
var
j:longint;
begin
if f[t,1]=0
then begin
flag:=true;
exit
end;
v[i]:=0;
inc(i);
vist(f[t,2]);
dec(i);
v[i]:=1;
inc(i);
vist(f[t,3]);
dec(i);
v[i]:=-1;
if flag
then begin
write(d1[t],':');
for j:=1 to i-1 do
write(v[j]);
writeln;
flag:=false
end;
end;
begin
readln(st);
n:=length(st);
for i:=1 to n do
inc(c[st[i]]);
j:=0;
for i:=1 to n do
if f1[st[i]]=false
then begin
inc(j);
a[j,1]:=c[st[i]];
a[j,2]:=j;
f[j,1]:=a[j,1];
d[j]:=st[i];
d1[j]:=st[i];
f1[st[i]]:=true
end;
fillchar(f1,sizeof(f1),false);
t:=n+1;
i:=j;
while i>1 do
begin
sort(i);
f[t,1]:=a[1,1]+a[2,1];
f[t,2]:=a[1,2];
f[t,3]:=a[2,2];
a[1,1]:=f[t,1];
a[1,2]:=t;
a[2,1]:=a[i,1];
a[2,2]:=a[i,2];
d[1]:=chr(110+t);
d[2]:=d[i];
inc(t); dec(i)
end;
fillchar(v,sizeof(v),255);
i:=1;
vist(t-1)
end.
Pixiv ID:60472266
本文介绍了一种基于字符频率构建哈夫曼树的方法,并通过具体示例展示了如何为不同的字符分配哈夫曼编码。该算法首先统计字符串中各字符的出现次数,然后根据这些频率值构造哈夫曼树。
1万+

被折叠的 条评论
为什么被折叠?



