數據結構中哈夫曼樹水題代碼

描述:

寫一個哈夫曼碼的編/譯碼系統,要求能對要傳輸的報文進行編碼和解碼。構造哈夫曼樹時,權值小的放左子樹,權值大的放右子樹,編碼時右子樹編碼爲1,左子樹編碼爲0.
 

輸入:

輸入表示字符集大小爲n(n <= 100)的正整數,以及n個字符和n個權值(正整數,值越大表示該字符出現的概率越大);
輸入串長小於或等於100的目標報文。

輸出:

經過編碼後的二進制碼,佔一行;
以及對應解碼後的報文,佔一行;
最後輸出一個回車符。

輸入樣例:

5 a b c d e 12 40 15 8 25 bbbaddeccbbb

輸出樣例:

00011111110111010110110000 bbbaddeccbbb

講道理還是蠻蠢的 搞了一個半小時

#include <cstdio>

#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
using namespace std;
struct Huffman_trie{
char a;
int deep;
int val;
int index;
Huffman_trie* left,*right;
friend bool operator<(Huffman_trie a,Huffman_trie b)
{
    return a.val>b.val;
}
}tree[1005];
map<char,int> mp;
Huffman_trie *root;
priority_queue <Huffman_trie> pq;
char str[1005];
map<char,int> dep;
void huffman()
{
    while(pq.size()>1)
    {
        Huffman_trie *h1 = (Huffman_trie*)malloc(sizeof(Huffman_trie));
        *h1 = pq.top();
        pq.pop();
        Huffman_trie *h2 = (Huffman_trie*)malloc(sizeof(Huffman_trie));
        *h2 = pq.top();
        pq.pop();
        Huffman_trie h3;
        h3.a=0;
        h3.left=h1;
        h3.right=h2;
        h3.val=h1->val+h2->val;
        pq.push(h3);
    }
    *root = pq.top();
    pq.pop();
    root->deep=0;
    root->index=0;
    queue <Huffman_trie>q;
    q.push(*root);
    while(!q.empty())
    {
        Huffman_trie ht=q.front();
        q.pop();
        if(ht.a!=0) {mp[ht.a]=ht.index; dep[ht.a]=ht.deep;}
        if(ht.left!=NULL)
        {
            ht.left->deep=ht.deep+1;
            ht.left->index=ht.index*10+0;
            q.push(*ht.left);
        }
        if(ht.right!=NULL)
        {
            ht.right->deep=ht.deep+1;
            ht.right->index=ht.index*10+1;
            q.push(*ht.right);
        }
    }
}
int main()
{
int n,c,d;
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf(" %c",&tree[i].a);
for(int i=0;i<n;i++)
{
scanf("%d",&tree[i].val);
pq.push(tree[i]);
}
scanf("%s",str);
root = (Huffman_trie*)malloc(sizeof(Huffman_trie));
huffman();
for(int i=0;i<strlen(str);i++)
printf("%0*d",dep[str[i]],mp[str[i]]);
printf("\n");
puts(str);
return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章