哈夫曼树

#include
#include
#include
using namespace std;
#define MAXINT 0x7fffffff
typedef struct treenode {
int left;
int right;
int parent;
int code;
int num;
};
treenode treenodes[60] = {0,0,0,0,0};
void dealWithInput(string str,int* w,int &count)
{
int i = 0;
int size = str.size();
for (i = 0; i < size; i++)
{
int k = 0;
if(str[i]>='A'&&str[i]<='Z')

  k = str[i] - 'A';
  if (w[k] == 0)
  count++;
  w[k]++;
}
else {
if (w[26] == 0)
count++;
w[26]++;
}
}
}
void huffman(int* w, int count)
{
int weight[29] = { 0 };
int i = 0,j=0;
int k = 1;
for (i = 0; i <=26; i++)
{
if (w[i] != 0)
{
weight[k++] = w[i];
}
}
for (i = 1; i <= 2 * count - 1; i++)
{

treenodes[i].left = 0;
treenodes[i].right = 0;
treenodes[i].parent = 0;
treenodes[i].code = 0;
if (i <= count)
treenodes[i].num = weight[i];
else {
treenodes[i].num = 0;
}

}
int m1, m2, x1, x2;
for (i = 1; i < count; i++)
{
m1 = MAXINT;
m2 = MAXINT;
x1 = -1;
x2 = -1;
for (j = 1; j < count + i;j++)
{
if (treenodes[j].num < m1&&treenodes[j].parent == 0)
{
m2 = m1;
x2 = x1;
m1 = treenodes[j].num;
x1 = j;
}
else if (treenodes[j].num < m2&&treenodes[j].parent == 0)
{
m2 = treenodes[j].num;
x2 = j;
}
}
treenodes[x1].parent = count + i;
treenodes[x2].parent = count + i;
treenodes[count + i].num = treenodes[x1].num + treenodes[x2].num;
treenodes[count + i].left = x1;
treenodes[count + i].right = x2;
}
int re = 0;
int ori = 0;
for (i = 1; i <= count; i++)
{
int p = treenodes[i].parent;
int temp = 0;
while (p != 0)
{
temp++;
p = treenodes[p].parent;
}
if (temp == 0)
temp = 1;
treenodes[i].code = temp;
re += (treenodes[i].num*temp);
ori += 8 * treenodes[i].num;
}
cout << ori << " " << re << " " <



}




int main()
{
//freopen("in.txt", "r", stdin);
string input;
while (cin >> input)
{
if (input.compare("END")==0)
{
break;
}
int w[27] = { 0 };
int count = 0;
dealWithInput(input, w, count);
huffman(w, count);
}
return 0;
}

你可能感兴趣的:(ACM)