하프만 인코딩과 하프만 트리의 실현 - Pascal 실현

2017 단어 Pascal
소스 코드:
program Project1;
type hu=RECORD
data:char;
weight:integer;
code:string;
end;
fun=record
weight,parent,Lc,Rc:integer;
end;
Var
tree:ARRAY[1..20] of hu;
newtree:ARRAY[1..20] of fun;
i,g,max,min,j,x:integer;
a:char;
s:string;
procedure inittree();
begin
i:=0;
read(a);
while(a<>'#') do begin
if(a>='0') and (a<='9') then begin
tree[i].weight:=tree[i].weight*10+ord(a)-ord('0');
end
else begin
inc(i);
tree[i].data:=a;
end;
read(a);
end;
g:=i;
end;
function minimum(im:integer):integer;
begin
min:=max;
x:=1;
for j:=1 to im-1 do
if(min>newtree[j].weight) and (newtree[j].parent=0)then
begin
min:=newtree[j].weight;
x:=j;
end;
newtree[x].parent:=im;
minimum:=x;
end;
procedure huffman;
begin
for i:=g+1 to 2*g-1 do
begin
newtree[i].Lc:=minimum(i);
newtree[i].Rc:=minimum(i);
newtree[i].weight:=newtree[newtree[i].Lc].weight+newtree[newtree[i].Rc].weight;
end;
writeln;
end;
procedure print_pre(n:integer);
begin
  write(tree[n].data);
  if(tree[2*n].data<>'#')then print_pre(2*n);
  if(tree[2*n+1].data<>'#')then print_pre(2*n+1);
end;
procedure println();
begin
for i:=1 to 2*g-1 do writeln(i:2,'|',newtree[i].weight:3,'|',newtree[i].parent:3,'|',newtree[i].Lc:2,'|',newtree[i].Rc:2);
end;
procedure getweight();
begin
for i:=1 to g do begin
newtree[i].weight:=tree[i].weight;
end;
end;
procedure printtree();
begin
for i:=1 to g do writeln(tree[i].data,' ',tree[i].weight);
end;
procedure MC(i:integer;x:integer);
begin
if(newtree[i].parent<>0) then begin
 MC(newtree[i].parent,i);
end;
begin
  if(x=newtree[i].Lc) then s:=s+'0'
  else s:=s+'1';
end;
end;
begin
max:=10000;
inittree;
for j:=1 to g do tree[j].code:='';
readln;
printtree;
getweight;
huffman;
println();
readln;
for j:=1 to g do begin
s:='';
MC(j,0);
tree[j].code:=copy(s,1,length(s)-1);
end;
for j:=1 to g do writeln(tree[j].data,':',tree[j].code);
readln;
end.

좋은 웹페이지 즐겨찾기