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

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

題解:離散中的“最小生成樹(最優樹)”。

#include <bits/stdc++.h>

using namespace std;

void qusort(int l, int r, int a[])
{
    int x = a[l];
    int i = l, j = r;
    if(i >= j)
        return ;
    while(i < j)
    {
        while(i < j && a[j] >= x)
            j --;
        a[i] = a[j];
        while(i < j && a[j] <= x)
            i ++;
        a[j] = a[i];
    }
    a[i] = x;
    qusort(l,i-1,a);
    qusort(i+1,r,a);
}
int main()
{
    char s[1000];
    int t[500];
    int q[1000];
    while(~scanf("%s", s))
    {
        int sum1 = 0;
        int sum2 = 0;
        memset(t,0,sizeof(t));
        int len = strlen(s);
        sum1 = 8 * len;
        for(int i = 0; i < len; i ++)
            t[s[i]] ++;
        int top = 0;
        int rear = 0;
        for(int i = 0; i < 500; i ++)
        {
            if(t[i] != 0)
                q[top ++] = t[i];
        }
        qusort(0,top-1,q);
        while(top != rear)
        {
            int x1 = q[rear ++];
            if(top != rear)
            {
                int x2 = q[rear ++];
                sum2 = sum2 + (x1 + x2);
                q[top ++] = x1 + x2;
                qusort(rear,top-1,q);
            }
        }
        printf("%d %d %.1lf\n", sum1, sum2, 1.0 * sum1 / sum2);
    }
    return 0;
}