思路:
参照哈夫曼编码,可以不用建树,用优先队列,每次把权值最小的两个加起来再入队,做到哈夫曼树的效果。
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<cmath>
#include<queue>
#include<vector>
using namespace std;
const int maxn = 1005;
char str[maxn];
struct node{
int x;
bool operator <(const node a)const{
return x>a.x;
}
}count[maxn];
int main(){
priority_queue<node>pq;
int sum=0;
while(scanf("%s",str)&&strcmp(str,"END")){
sum=0;
memset(count,0,sizeof(count));
for(int i=0;i<strlen(str);i++){
count[str[i]].x++;
}
for(int i=0;i<200;i++){
if(count[i].x){
pq.push(count[i]);
count[i].x=0;
}
}
while(pq.size()>1){
node temp1=pq.top();
pq.pop();
node temp2=pq.top();
pq.pop();
sum+=temp1.x+temp2.x;
pq.push(node{temp1.x+temp