http://acm.hdu.edu.cn/showproblem.php?pid=1053

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring> 
#include <queue> 

using namespace std; 

int a[30];

char s[1005];

int cal(char x){
    if(x == '_') return 0; 
    else return x - 'A' + 1;
}

struct node{
    int w;
    friend bool operator <(node aa, node bb){
        return aa.w > bb.w; 
    }
};

int main(){
    while(~scanf("%s", s)){
        if(!strcmp(s,"END")) break; 
        int len = strlen(s); 
        memset(a, 0, sizeof(a));
        for(int i = 0; i < len; i++){
            a[cal(s[i])]++; 
        }
        priority_queue <node> q; 
        for(int i = 0; i < 27; i++){
            node b;
            b.w = a[i];
            if(a[i]) q.push(b); 
        }
        int res; 
        if(q.size() == 1) res = len;
        else{
            res = 0; 
            while(q.size() > 1){
                int aa = q.top().w; q.pop(); 
                int bb = q.top().w; q.pop(); 
                res += (aa + bb);
                node b;
                b.w = aa + bb;
                q.push(b);
            }
        }
        printf("%d %d %.1lf\n", len*8, res, len*8.0/res); 
    }
    return 0;
}
View Code

http://acm.hdu.edu.cn/showproblem.php?pid=2527

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring> 
#include <queue> 

using namespace std; 

int a[30];

char s[1005];

int cal(char x){
    return x - 'a' + 1;
}

struct node{
    int w;
    friend bool operator <(node aa, node bb){
        return aa.w > bb.w; 
    }
};

int main(){
    int n;
    scanf("%d", &n);
    while(n--){
        int m;
        scanf("%d %s", &m, s);
        int len = strlen(s); 
        memset(a, 0, sizeof(a));
        for(int i = 0; i < len; i++){
            a[cal(s[i])]++; 
        }
        priority_queue <node> q; 
        for(int i = 1; i < 27; i++){
            node b;
            b.w = a[i];
            if(a[i]) q.push(b); 
        }
        int res; 
        if(q.size() == 1) res = len;
        else{
            res = 0; 
            while(q.size() > 1){
                int aa = q.top().w; q.pop(); 
                int bb = q.top().w; q.pop(); 
                res += (aa + bb);
                node b;
                b.w = aa + bb;
                q.push(b);
            }
        }
        if(res <= m) puts("yes");
        else puts("no");
    }
    return 0;
}
View Code

两道几乎相同的题,哈夫曼编码的长度是合出来的各个节点之和(只剩一个节点停止),开始每个节点的权值是字符出现的频率,如果开始只有一个节点的情况要特判