1. 程式人生 > >資料結構實驗之二叉樹六:哈夫曼編碼

資料結構實驗之二叉樹六:哈夫曼編碼

SDUT oj 2127

這道題是典型的最優二叉樹問題

像下面的程式碼一樣,看水過去了吧

#include <vector>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int main()
{
    int n;
    char a[100005];
    while(~scanf("%s",a))
    {
        int v[10005];
        memset(v,0,sizeof(v));
        long long int ans=0;
        priority_queue<int ,vector<int >,greater<int > >que;
        for(int i=0; i<strlen(a); i++)
        {
            v[a[i]]++;
        }
        for(int i=1;i<200;i++)
        {
            if(v[i]!=0)
            {
                que.push(v[i]);
            }
        }
        int n=strlen(a)*8;
        while(que.size()>1)
        {
            int j,k;
            j=que.top();
            que.pop();
            k=que.top();
            que.pop();
            ans+=(j+k);
            que.push(j+k);
        }
        printf("%d %lld %.1f\n",n,ans,(n*1.0/ans));
    }
}