Advertisement
Guest User

huffman coding

a guest
May 25th, 2015
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. #include<cstdio>
  2. #include<cstdlib>
  3. #include<cstring>
  4. using namespace std;
  5. int frequency[200];
  6. struct node
  7. {
  8. char c;
  9. int fre;
  10. node *lf,*rf;
  11. };
  12.  
  13. node *store[1000],*now,*n1,*n2;
  14. char codes[200][50];
  15. void encode(node *head,char code[])
  16. {
  17. if(head->c!='0')
  18. {
  19. printf("%c %s\n",head->c,code);
  20. strcpy(codes[head->c],code);
  21. return;
  22. }
  23. char cl[50];
  24. strcpy(cl,code);
  25. strcat(cl,"0");
  26. encode(head->lf,cl);
  27. char cr[50];
  28. strcpy(cr,code);
  29. strcat(cr,"1");
  30. encode(head->rf,cr);
  31. }
  32. int main()
  33. {
  34. freopen("source.txt", "r", stdin);
  35. freopen("charcode.txt", "w", stdout);
  36. char c;
  37. int count=0,total=0,i;
  38. while(scanf("%c",&c)==1)
  39. {
  40. frequency[c]++;
  41. total++;
  42. }
  43.  
  44. for(i='a';i<='z';i++)
  45. {
  46. now=(node*)malloc(sizeof(node));
  47. now->fre=frequency[i];
  48. now->c=i;
  49. store[count++] = now;
  50. }
  51. now=(node*)malloc(sizeof(node));
  52. now->fre=frequency[' '];
  53. now->c=' ';
  54. store[count++] = now;
  55. int elements=count-1;
  56. int min,minode;
  57. while(elements--)
  58. {
  59. min=10000000,minode=-1;
  60. for(i=0;i<count;i++)
  61. {
  62. if(store[i]!=NULL&&store[i]->fre<min)
  63. {
  64. min=store[i]->fre;
  65. minode=i;
  66. }
  67. }
  68. n1=store[minode];
  69. store[minode]=NULL;
  70. min=10000000,minode=-1;
  71. for(i=0;i<count;i++)
  72. {
  73. if(store[i]!=NULL&&store[i]->fre<min)
  74. {
  75. min=store[i]->fre;
  76. minode=i;
  77. }
  78. }
  79. n2=store[minode];
  80. store[minode]=NULL;
  81. now=(node*)malloc(sizeof(node));
  82. now->fre=n1->fre+n2->fre;
  83. now->c='0';
  84. now->lf=n1;
  85. now->rf=n2;
  86. store[count++]=now;
  87. }
  88. node *tree=store[count-1];
  89. char str[]="";
  90. encode(tree,str);
  91. freopen("source.txt", "r", stdin);
  92. freopen("output.txt", "w", stdout);
  93. while(scanf("%c",&c)==1)
  94. {
  95. printf("%s",codes[c]);
  96. }
  97. //while(1);
  98. return 0;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement