数据结构实验之二叉树六:哈夫曼编码(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
", sum1, sum2, 1.0 * sum1 / sum2);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/lcchy/p/10139444.html