程序代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _LETTER
{
int weight;
int index;
char str[28];
} LETTER;
int compare(const void *a, const void *b)
{
LETTER *p1, *p2;
p1 = (LETTER *)a;
p2 = (LETTER *)b;
return p2->weight - p1->weight;
}
void main()
{
LETTER let[52];
int i, offset;
for (i=0; i<26; i++)
{
scanf("%s%d", let[i].str, &let[i].weight);
let[i].index = 0;
}
qsort(let, 26, sizeof(LETTER), compare);
for (i=25; i>0; i--)
{
memcpy(&let[i*2+1], &let[i], sizeof(LETTER));
memcpy(&let[i*2], &let[i-1], sizeof(LETTER));
strcat(let[i-1].str, let[i*2+1].str);
let[i-1].weight += let[i*2+1].weight;
let[i-1].index = i*2;
memset(&let[i], 0, sizeof(LETTER));
qsort(let, i, sizeof(LETTER), compare);
}
char code[] = "10110001011100101001111101111110010100111101100101001100111111000";
offset = 2;
for (i=0; i<strlen(code); i++)
{
offset += '1' - code[i];
if (strlen(let[offset].str) == 1)
{
printf("%c", let[offset].str[0]);
offset = 2;
}
else
{
offset = let[offset].index;
}
}
printf("\n");
if (offset != 2)
{
printf("error\n");
}
}
输入:
A 819
B 147
C 383
D 391
E 1225
F 226
G 171
H 457
I 710
J 14
K 41
L 377
M 334
N 706
O 726
P 289
Q 9
R 685
S 636
T 941
U 258
V 109
W 159
X 21
Y 158
Z 8