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;
}