暑期多校联赛K题 哈夫曼树编码

K、Encode                             Time limit:               1.000 seconds
Given a string S, you need to use N different characters will be encoded into a string.
Input
Line 1: S Waiting for the encoded string (length<=100000 )
Line 2: N N characters to encode the S (N different characters 0<=N<=100000)
Output:
You need to print the length of the encoded
Sample Input
iloveacm
2 iloveacm
4
Sample Output
24
14

 

 

题目大意:哈夫曼树编码

思路:虚节点的加入巧妙方便运算

 

program:

#include <algorithm>
#include <set>
#include <vector>
using namespace std;

int main() {
    int n, m, t;
    static char buf[1 << 20];
while (gets(buf) != NULL) 
{
        vector<int> wc(128);
        for (int i = 0; buf[i] != '\0'; ++i) 
        {
            ++wc[buf[i]];
        }
        wc.erase(remove(wc.begin(), wc.end(), 0), wc.end());
        scanf("%d%*c",&n);
        while ((int)wc.size() % (n - 1) != 1 % (n - 1))
          {
            wc.push_back(0);//虚节点的补充,这样子才方便建树 
          }
  
        multiset<int> s(wc.begin(), wc.end());
        m = s.size() == 1 ? *s.begin() : 0;
        while (s.size() > 1)
         {
            t = 0;
            for (int i = 0; i < n; ++i)
            {
                t += *s.begin();
                s.erase(s.begin());
            }
            s.insert(t);
            m += t;
        }
        printf("%d\n", m);
}
    return 0;
}


 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值