Problem Description
Javac++ 一天在看计算机的书籍的时候,看到了一个有趣的东西!每一串字符都可以被编码成一些数字来储存信息,但是不同的编码方式得到的储存空间是不一样的!并且当储存空间大于一定的值的时候是不安全的!所以Javac++ 就想是否有一种方式是可以得到字符编码最小的空间值!显然这是可以的,因为书上有这一块内容–哈夫曼编码(Huffman Coding);一个字母的权值等于该字母在字符串中出现的频率。所以Javac++ 想让你帮忙,给你安全数值和一串字符串,并让你判断这个字符串是否是安全的?
Input
输入有多组case,首先是一个数字n表示有n组数据,然后每一组数据是有一个数值m(integer),和一串字符串没有空格只有包含小写字母组成!
Output
如果字符串的编码值小于等于给定的值则输出yes,否则输出no。
Sample Input
2
12
helloworld
66
ithinkyoucandoit
Sample Output
no
yes
| 思路:无需建立哈夫曼树,采用优先级队列模拟 |
#include<iostream>
#include<cstring>
#include<stack>
#include<queue>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
const int MAXN = 1e5 + 50;
#define mem(a,b) memset(a,b,sizeof(a))
#define rep(i,x) for(int i=0;i<x;++i)
inline int in() {
char ch = getchar();
int f = 1, x = 0;
while (ch < '0' || ch > '9') {
if (ch == '-')
f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
x = (x << 1) + (x << 3) + ch - '0', ch = getchar();
return f * x;
}
int cnt[27],T,n;
string s;
int main()
{
T=in();
while(T--){
mem(cnt,0);
n=in();
cin>>s;
int m = s.size();
rep(i,m){
cnt[s[i]-'a']++;
}
priority_queue<int,vector<int>,greater<int>> Q; //小顶堆
rep(i,26){
if(cnt[i])
Q.push(cnt[i]);
}
int sum = 0;
if(Q.size() == 1) { //注意特判只有一种字符的情况
sum = Q.top();Q.pop();
}
while(Q.size() > 1){
int a = Q.top(); Q.pop();
int b = Q.top(); Q.pop();
sum+=(a+b);
Q.push(a+b);
}
if(sum <= n) puts("yes");
else puts("no");
}
return 0;
}
本文介绍了一种利用哈夫曼编码评估字符串安全性的问题解决方法。通过优先级队列模拟哈夫曼树构建过程,计算字符串编码所需最小空间,以此判断其是否安全。
168

被折叠的 条评论
为什么被折叠?



