哈夫曼树的初级应用~~
忘记了,可以看看算法导论,里面讲的很详细~~
很经典的一个处理方法,利用优先队列来处理。值得思考
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
struct tr
{
int t;
friend bool operator <(tr a,tr b){ //自定义优先级,升序排列
return a.t>b.t;
}
};
char s[10000];
int sev[30];
int main()
{
int t;
priority_queue <tr> q;
cin>>t;
while(t--)
{
int sum(0),n,lens;
tr ts;
memset(sev,0,sizeof(sev));
cin>>n>>s;
lens=strlen(s);
for(int i=0;i<lens;i++)
sev[s[i]-'a']++;
while(q.size()!=0) q.pop();
for(int i=0;i<=27;i++)
if(sev[i]){
tr c;
c.t=sev[i];
q.push(c);
}
if(q.size()==1){
if(lens<=n) cout<<"yes"<<endl;
else cout<<"no"<<endl;
continue;
}
while(q.size()!=1) //稍微注意一下
{
tr c,a,b;
a=q.top(); q.pop();
b=q.top(); q.pop();
c.t=a.t+b.t;
sum+=c.t;
q.push(c);
}
if(n>=sum) cout<<"yes"<<endl;
else cout<<"no"<<endl;
}
return 0;
}