今天看数据结构,看到哈夫曼编码。感觉挺有意思的。哈夫曼树的应用应该很多吧,还刚学,以后多深入看看。
#include <iostream>
#include <cstdio>
#include <stack>
#include <algorithm>
#include <queue>
//#include <functional>
#include <cstring>
#define Max 100000000
using namespace std;
struct node
{
int ww;
int parent,left,right;
};
struct pp
{
int m;
int root;
node head[100];
};
int x[50];
string y[50];
pp Huffman(int m)
{
pp shu;
shu.m=m;
int m1=Max,m2=Max;
for (int number=0;number<2*m-1;number++)
{
shu.head[number].ww=-1,shu.head[number].parent=-1,shu.head[number].left=-1,
shu.head[number].right=-1;
if(number<m)
{
shu.head[number].ww=x[number];
}
}
for (int number1=0;number1<m-1;number1++)
{
int x1=-1,x2=-1;
m1=Max,m2=Max;
for (int number2=0;number2<number1+m;number2++)
{
if (shu.head[number2].ww<m1&&shu.head[number2].parent==-1)
{
x2=x1,m2=m1;
x1=number2;
m1=shu.head[number2].ww;
}
else if (shu.head[number2].ww<m2&&shu.head[number2].parent==-1)
{
x2=number2;
m2=shu.head[number2].ww;
}
}
shu.head[x1].parent=m+number1;
shu.head[x2].parent=m+number1;
shu.head[m+number1].left=x1;
shu.head[m+number1].right=x2;
shu.head[m+number1].ww=m1+m2;
}
return shu;
}
void qian(pp shu,int num,string all)
{
string p=all;
int flag=0;
if (shu.head[num].left!=-1)
{
flag=1;
all+='0';
qian(shu,shu.head[num].left,all);
}
if (shu.head[num].right!=-1)
{
if (flag==1)all=p;
all+='1';
qian(shu,shu.head[num].right,all);
}
if (shu.head[num].left==-1&&shu.head[num].right==-1)
{
y[num]=all;
}
}//用来输出哈夫曼编码的。