哈夫曼数 c++

来源:互联网 发布:mac 隐藏文件夹 编辑:程序博客网 时间:2024/05/18 17:05
#include<iostream>
#include<string>
using namespace std;
#define M 100
/*weight:该结点的权值。
lchild:该结点的左孩子结点在数组中的下标。
rchild:该结点的右孩子结点在数组中的下标。
parent:该结点的双亲结点在数组中的下标。*/

struct element
{
double weight;
int lchild, rchild, parent;
};
element huffTree[M];

//初始化,输入数组的权值,将结构体中其他未知的赋值为-1
void init(int x){
for(int i=0;i<2*x-1;i++){
if(i<x){
cout<<"第"<<i<<"个节点:权值"<<" ";
cin>>huffTree[i].weight;
}
else{
huffTree[i].weight=-1;
}
huffTree[i].lchild=-1;
huffTree[i].rchild=-1;
huffTree[i].parent=-1;
}
}

//输出哈夫曼树数组
void output(int x){
for(int i=0;i<2*x-1;i++){
cout<<"第"<<i<<"个节点:权值"<<" "<<huffTree[i].weight<<" 左孩子"<<huffTree[i].lchild<<" 右孩子"<<huffTree[i].rchild<<" 双亲"<<huffTree[i].parent<<endl;
}
}

//求哈夫曼编码并输出
void HuffmanCode(element huffTree[],int n)
{
int j=0;
for(int i=0;i<n;i++){
string s="";
//在数组huffTree中前n个元素是叶子结点
   j=i;
   while(huffTree[j].parent!=-1){
int a=huffTree[i].parent;
if(huffTree[a].lchild==j) s.append("0");
else s.append("1");
j=huffTree[j].parent;
   }
   //将s作为结点i的编码逆序输出;
int x=s.length();
cout<<"第"<<i<<"个节点的哈夫曼编码:";
for(int z=x;z>=0;z--){
cout<<s[z];
}
cout<<endl;
// cout<<s<<endl;
}
}


void main(){
int x;
cout<<"请输出哈夫曼树的节点个数:";
cin>>x;
init(x);
int visited[M];//数组:记录节点是否被访问了 0 未访问  1已访问
for(int z=0;z<2*x-1;z++){
visited[z]=0; //初始化数组
}
int flag=huffTree[2*x-2].weight;
while(flag==-1){
//找大小
int p1,p2,small1,small2;
p1=p2=-1; //最小和次小下标
small1=small2=M;//最小与次小的值
for(int j=0;j<2*x-1;j++){
if(visited[j]==0&&huffTree[j].weight!=-1){
//没有取过,可比较
if(huffTree[j].weight<small1) {//修改最小、次小及位置
small2=small1;
small1=huffTree[j].weight;
p2=p1;p1=j;
}
else if(huffTree[j].weight<small2) {//修改次小及位置
small2=huffTree[j].weight;
p2=j;
}
}
}
visited[p1]=visited[p2]=1;
int add=small1+small2;//双亲节点的权值
int a=0;
while(a<2*x-1){//记录双亲节点
if(huffTree[a].weight==-1){
huffTree[a].weight=add;
huffTree[a].lchild=p1;
huffTree[a].rchild=p2;
huffTree[p1].parent=a;
huffTree[p2].parent=a;
break;
}
else ++a;
}
flag=huffTree[2*x-2].weight;
}
cout<<endl;
output(x);
HuffmanCode(huffTree,x);
cout<<endl;
}
原创粉丝点击