Huffman树:
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<string.h>
using namespace std;
typedef long long ll;
struct huffmanNode
{
int weight;
int parent,lchild,rchild;
}tree[1100];
int n,w[1100],root;
void Select (int pos, int &x1, int &x2)
{
int m1 = 999999999, m2 = 999999999; /* 相关变量赋初值 */
for (int j=1; j<pos; j++) {/* 找两个最小权的无父结点的结点 */
if (tree[j].weight<m1 && tree[j].parent == 0) {
m2 = m1;
x2 = x1;
m1 = tree[j].weight;
x1 = j;
}
else if (tree[j].weight<m2 && tree[j].parent == 0) {
m2 = tree[j].weight;
x2 = j;
}
}
}
void huffman ()
{
for(int i=1;i<=2*n-1;i++)
{
tree[i].lchild=0;
tree[i].rchild=0;
tree[i].parent=0;
if(i<=n)
tree[i].weight=w[i];
else
tree[i].weight=0;
}
int x1,x2;
for(int i=1; i < n ; i++ )
{
Select (n+i, x1, x2);
cout<<x1<<" "<<x2<<endl;
tree[x1].parent = n + i; /* 构造一个内部结点 */
tree[x2].parent = n + i;
tree[n+i].weight = tree[x1].weight + tree[x2].weight;
tree[n+i].lchild = x1;
tree[n+i].rchild = x2;
root = n+i;
}
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++) cin>>w[i];
huffman();
cout<<tree[root].weight;
}
8
a b c d e f g h
5 25 3 6 10 11 36 4
huffman编码:
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<string>
using namespace std;
typedef long long ll;
struct huffmanNode
{
char ch;
int weight;
int parent,lchild,rchild;
}tree[1100];
struct mumber
{
char ch;
int w;
string s;
}a[1100];
int n,root;
string ss="";
void Select (int pos, int &x1, int &x2)
{
int m1 = 999999999, m2 = 999999999;
for (int j=1; j<pos; j++) {
if (tree[j].weight<m1 && tree[j].parent == 0) {
m2 = m1;
x2 = x1;
m1 = tree[j].weight;
x1 = j;
}
else if (tree[j].weight<m2 && tree[j].parent == 0) {
m2 = tree[j].weight;
x2 = j;
}
}
}
void huffman ()
{
for(int i=1;i<=2*n-1;i++)
{
tree[i].lchild=0;
tree[i].rchild=0;
tree[i].parent=0;
if(i<=n)
{tree[i].weight=a[i].w;tree[i].ch=a[i].ch;}
else
{tree[i].weight=0;tree[i].ch='\n';}
}
int x1,x2;
for(int i=1; i < n ; i++ )
{
Select (n+i, x1, x2);
//cout<<x1<<" "<<x2<<endl;
tree[x1].parent = n + i;
tree[x2].parent = n + i;
tree[n+i].weight = tree[x1].weight + tree[x2].weight;
tree[n+i].lchild = x1;
tree[n+i].rchild = x2;
root = n+i;
}
}
void dfs(string s,int x)
{
if(tree[x].ch!='\n')
for(int i=1;i<=n;i++)
if(a[i].ch==tree[x].ch)
{
a[i].s=s;
//cout<<s<<endl;
break;
}
if(tree[x].lchild==0&&tree[x].rchild==0) return;
if(tree[x].lchild)
{
s.push_back('0');
dfs(s,tree[x].lchild);
s.erase(s.end() - 1);
}
if(tree[x].rchild)
{
s.push_back('1');
dfs(s,tree[x].rchild);
s.erase(s.end() - 1);
}
}
void init()
{
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i].ch;
for(int i=1;i<=n;i++)
cin>>a[i].w;
}
int main()
{
init();
huffman();
//cout<<tree[root].weight<<endl;
dfs(ss,root);
cin>>ss;
int m=ss.length();
for(int i=0;i<m;i++)
for(int j=1;j<=n;j++)
if(ss[i]==a[j].ch)
{
cout<<a[j].s;
break;
}
printf("\n");
cout<<ss<<endl;
//cout<<a[1].s;
/*for(int i=1;i<=n;i++)
cout<<a[i].ch<<" "<<a[i].s<<endl;*/
}