Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <malloc.h>
- #include <string.h>
- using namespace std;
- typedef struct
- {
- unsigned int weight;
- unsigned int parent, lchild, rchild;
- } Htnode, *HuffmanTree;
- #define MAX 100;
- #define max 65535;
- typedef char **HuffmenCode;
- void Select(HuffmanTree &HT, int x, int &s1, int &s2)
- {
- unsigned int min1 = max;
- unsigned int min2 = max;
- for (int i = 1; i <= x; i++)
- {
- if (HT[i].weight < min1 && HT[i].parent == 0)
- {
- min1 = HT[i].weight;
- s1 = i;
- }
- }
- for (int i = 1; i <= x; i++)
- {
- if (HT[i].weight < min2 && i != s1 && HT[i].parent == 0)
- {
- min2 = HT[i].weight;
- s2 = i;
- }
- }
- }
- void HuffmanCoding(HuffmanTree &HT, HuffmenCode &HC, int w[], int n)
- {
- int s1, s2;
- if (n <= 1) return ;
- int m = 2 * n - 1;
- HT = (HuffmanTree)malloc((m + 1) * sizeof(Htnode));
- for (int i = 1; i <= n; i++)
- {
- HT[i].weight = w[i - 1];
- HT[i].parent = 0;
- HT[i].lchild = 0;
- HT[i].rchild = 0;
- }
- for (int i = n + 1; i <= m; i++)
- {
- HT[i].weight = 0;
- HT[i].parent = 0;
- HT[i].lchild = 0;
- HT[i].rchild = 0;
- }
- for (int 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 = (HuffmenCode)malloc((n + 1) * sizeof(char *));
- char *cd = (char *)malloc(n * sizeof(char));
- cd[n - 1] = '\0';
- for (int i = 1; i <= n; i++)
- {
- int start = n - 1;
- unsigned int c, f;
- for (c = i, f = HT[i].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]);
- }
- free(cd);
- }
- int main()
- {
- HuffmanTree HT;
- HuffmenCode HC;
- int n;
- int w[100];
- cin >> n;
- for (int i = 0; i < n; i++)
- {
- cin >> w[i];
- }
- HuffmanCoding(HT, HC, w, n);
- for (int i = 1; i <= n; i++)
- {
- cout << HC[i] << endl;
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment