哈夫曼編碼
問題描述
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
priority_queue <int, vector <int>, greater<int> > q;
int a[30];
int ans = 0;
void create() {
int a, b;
while (q.size() > 1) {
a = q.top(); q.pop();
b = q.top(); q.pop();
ans += a + b;
q.push(a + b);
}
if (ans == 0) {
ans = q.top();
}
}
int main() {
string s;
int T;
cin >> T;
while (T--) {
int n;
cin >> n;
cin >> s;
memset(a, 0, sizeof(a));
while (!q.empty()) q.pop();
ans = 0;
for (int i = 0; i < s.size(); i++) {
a[s[i] - 'a']++;
}
for (int i = 0; i < 30; i++) {
if (a[i]) {
q.push(a[i]);
}
}
create();
if (ans <= n) {
cout << "yes" << endl;
}
else {
cout << "no" << endl;
}
}
return 0;
}