데이터 구조 - 트 리 와 이 진 트 리 의 기본 연산 실현
프로그램 exp7 - 6. cpp 를 설계 하여 하프 만 트 리 를 구성 하고 출력 에 대응 하 는 하프 만 인 코딩 과 평균 검색 길 이 를 설정 합 니 다.표 7.8 에서 보 여 준 데이터 로 검증 한다.
실험 목적
하프 만 나무의 구조 과정 과 하프 만 인 코딩 의 생 성 방법 파악 하기;이 진 트 리 라 는 데이터 구 조 를 활용 하여 종합 적 인 응용 문 제 를 해결 하 다.
원본 코드:
#include <iostream>
#include <cstring>
#define N 50
#define M 2*N-1
using namespace std;
struct HTNode
{
char data[5]; //
int weight;
int parent;
int lchild;
int rchild;
};
struct HCode
{
char cd[N]; //
int start;
};
void CreateHT(HTNode ht[],int n)
{
int i,k,lnode,rnode;
int min1,min2;
for (i=0;i<2*n-1;i++)
ht[i].parent=ht[i].lchild=ht[i].rchild=-1;
for (i=n;i<2*n-1;i++)
{
min1=min2=32767;
lnode=rnode=-1;
for (k=0;k<=i-1;k++)
if (ht[k].parent==-1)
{
if (ht[k].weight<min1)
{
min2=min1;rnode=lnode;
min1=ht[k].weight;lnode=k;
}
else if (ht[k].weight<min2)
{
min2=ht[k].weight;rnode=k;
}
}
ht[lnode].parent=i;ht[rnode].parent=i;
ht[i].weight=ht[lnode].weight+ht[rnode].weight;
ht[i].lchild=lnode;ht[i].rchild=rnode;
}
}
void CreateHCode(HTNode ht[],HCode hcd[],int n)
{
int i,f,c;
HCode hc;
for (i=0;i<n;i++)
{
hc.start=n;c=i;
f=ht[i].parent;
while (f!=-1)
{
if (ht[f].lchild==c)
hc.cd[hc.start--]='0';
else
hc.cd[hc.start--]='1';
c=f;f=ht[f].parent;
}
hc.start++;
hcd[i]=hc;
}
}
void DispHCode(HTNode ht[],HCode hcd[],int n)
{
int i,k;
int sum=0,m=0,j;
cout<<" :"<<endl;
for (i=0;i<n;i++)
{
j=0;
cout<<ht[i].data<<":";
for (k=hcd[i].start;k<=n;k++)
{
cout<<hcd[i].cd[k];
j++;
}
m+=ht[i].weight;
sum+=ht[i].weight*j;
cout<<endl;
}
cout<<" ="<<1.0*sum/m<<endl;;
}
int main()
{
int n=15,i;
char *str[]={"The","of","a","to","and","in","that","he","is","at","on","for","His","are","be"};
int fnum[]={1192,677,541,518,462,450,242,195,190,181,174,157,138,124,123};
HTNode ht[M];
HCode hcd[N];
for (i=0;i<n;i++)
{
strcpy(ht[i].data,str[i]);
ht[i].weight=fnum[i];
}
CreateHT(ht,n);
CreateHCode(ht,hcd,n);
DispHCode(ht,hcd,n);
}
실행 결과:
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
알고리즘 시리즈 (7) 데이터 구조의 트 리 의 기본 구조 와 이 진 트 리 의 옮 겨 다 니 기각 노드 에 0 개 이상 의 키 노드 가 있다.부모 노드 가 없 는 노드 를 뿌리 노드 라 고 한다.모든 비 근 노드 가 있 고 부모 노드 만 있 습 니 다.뿌리 노드 를 제외 하고 모든 하위 노드 는 서로 교차 하...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.