#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct HTNode{
char c;
int weight;
int parent,lchild,rchild;
}HTNode,*HuffmanTree;
typedef char **HuffmanCode;
HuffmanTree CreatHuffmanTree( int n);
void Select(HuffmanTree HT,int i,int *s1,int *s2);
void CreatHuffmanCode(HuffmanTree *HT, int n);
void EnCoding(HuffmanTree HT,HuffmanCode HC,int n);
int main()
{
int n;
scanf("%d",&n);
getchar();
HuffmanTree HT;
HT=CreatHuffmanTree(n);
HuffmanCode HC;
CreatHuffmanCode(&HT, n);
EnCoding(HT,HC,n);
return 0;
}
HuffmanTree CreatHuffmanTree( int n) //creat a huffmantree which is HT
{
int s1 , s2,j,k=1;
if(n <= 1)
return ;
int m = 2*n-1 ;
HuffmanTree HT;
HT =(HuffmanTree)malloc(sizeof(HTNode)*(m+1));
for(int i = 1;i <= m;i++)
{
HT[i].parent = 0;
HT[i].lchild = 0;
HT[i].rchild = 0;
}
for(int i = 1;i <= n;i++)
{
scanf("%c%d",&HT[i].c,&HT[i].weight);
}
for(int i = n+1;i <= m;++i)
{
while(HT[k].parent!=0) //s2 is the second least of HT[].weight
k++;
s1=k;
for(j=1;j<=i-1;++j)
if(HT[j].parent==0&&HT[j].weight<HT[s1].weight)
s1=j;
k=1;
while((HT[k].parent!=0||k==s1))
k++;
s2=k;
for(j=1;j<=i-1;++j)
if(HT[j].parent==0&&HT[j].weight<HT[s2].weight&&j!=s1)
s2=j;
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;
}
return HT;
}
void CreatHuffmanCode(HuffmanTree *HT, int n) // Create the HuffmanCode
{
int start,c,f;
char *cd;
HuffmanCode HC;
HC =(HuffmanCode)malloc(sizeof(char*)*(n+1));
cd = (char*)malloc(n*sizeof(char));
cd[n-1] = '\0';
for (int i = 1;i <= n;i++)
{
start = n-1;
c = i;
f = (*HT)[i].parent;
while (f != 0)
{
start--;
if((*HT)[f].lchild == c)
cd[start] = '0';
else
cd[start] = '1';
c = f;
f = (*HT)[f].parent;
}
HC[i] = (char*)malloc((n-start)*sizeof(char));
strcpy(HC[i],&cd[start]);
printf("%c's Huffman code is: %s",(*HT)[i].c,HC[i]);
printf("\n");
}
free(cd);
}
void EnCoding(HuffmanTree HT,HuffmanCode HC,int n)
{
int len,i,j;
char str[1000];
scanf("%s",str);
len = strlen(str);
for(i = 0;i<len;i++)
{
for(j=1;j<=n;j++)
{
if(str[i] == HT[j].c)
printf("%s",HC[j]);
}
}
printf("\n");
}