送20分。。麻烦高手帮忙改错。。。
应该是蛮白痴的错误。。但是最近大脑故障了。麻烦帮忙看看。//HuffmanCode
#include <iostream>
#include <string.h>
#define MAXSIZE 15
using namespace std;
typedef struct
{
unsigned int weight;
unsigned int parent, lchild, rchild;
}HTNode, *HuffmanTree;
typedef char **HuffmanCode;
void Select(HuffmanTree &HT, int n, int &s1, int &s2)
{
//选择HT[1..n]中parent为0且weight最小的两个结点
//序号分别赋值给s1,s2
int tmp;
for (int i = 1; i <= n; i++)
if (HT[i].parent == 0)
{
s1 = i;
break;
}
for (; i <= n; i++)
if (HT[i].parent == 0)
{
s2 = i;
break;
}
if (HT[s1].weight > HT[s2].weight)
{
tmp = s1;
s1 = s2;
s2 = tmp;
}
for (; i <= n; i++)
if (HT[i].parent == 0 && HT[i].weight < HT[s2].weight)
if (HT[i].weight < HT[s1].weight)
{
tmp = s1;
s1 = i;
s2 = tmp;
}
else
s2 = i;
}
void HuffmanCoding(HuffmanTree &HT, HuffmanCode &HC, int *w, int n)
{
//建立哈夫曼树,求哈夫曼编码
HuffmanTree p;
char *cd;
int i, s1, s2, start;
unsigned int c, f;
if (n <= 1)
return;
int m = 2 * n - 1;
HT = (HuffmanTree) malloc((m + 1) * sizeof(HTNode));
for (p = HT, i = 1; i <= n; ++i, ++p, ++w)
{
p->weight = *w;
p->parent = 0;
p->lchild = 0;
p->rchild = 0;
}
for (; i <= m; ++i, ++p)
{
p->weight = 0;
p->parent = 0;
p->lchild = 0;
p->rchild = 0;
}
for (i = n + 1; i <= m; ++i)
{
Select(HT, i-1, s1, s2);
HT[s1].parent = i;
HT[s2].parent = i;
HT[i].lchild = s1;
HT[i].rchild = s2;
HT[i].weight = HT[s1].weight + HT[s2].weight;
}
HC = (HuffmanCode) malloc((n+1) * sizeof(char *));
cd = (char *) malloc(n * sizeof(char));
cd[n-1] = '\0';
for (i = 1; i <= n; ++i)
{
start = n - 1;
for (c = i, f = HT[c].parent; f != 0; c = f, f = HT[f].parent)
if (HT[f].lchild == c)
cd[--start] = '0';
else
cd[--start] = '1';
HC[i] = (char *) malloc((n - start) * sizeof(char));
strcpy(HC[i], &cd[start]);
printf("%s\n", HC[i]);
}
free(cd);
}
int main()
{
HuffmanTree HT;
HuffmanCode HC;
int w[MAXSIZE], n;
cout << "请输入字符数目\n";
cin >> n;
cout << "请输入各字符的权值\n";
for (int i = 0; i < n; i++)
cin >> w[i];
HuffmanCoding(HT, HC, w, n);
return 0;
}