类似HuffMan编码。
CODE:
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <queue>
using namespace std;
#define MAXN 1001
priority_queue<int , vector<int>, greater<int> > q;
char str[MAXN];
int huf[MAXN];
int n;
void solve()
{
int ans = 0, a, b;
while(q.size() != 1)
{
a = q.top(); q.pop();
b = q.top(); q.pop();
q.push(a+b);
ans += (a+b);
}
printf(ans <= n?"yes\n":"no\n");
}
void init()
{
while(!q.empty()) q.pop();
memset(huf, 0, sizeof(huf));
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
init();
scanf("%d", &n);
scanf("%s", str);
for(int i = 0; str[i]; i++)
{
huf[str[i]-'a']++;
}
for(int i = 0; i < 26; i++) if(huf[i])
{
q.push(huf[i]);
}
if(q.size() == 1)
{
int a = q.top(); q.pop();
printf(a <= n?"yes\n":"no\n");
continue;
}
solve();
}
return 0;
}
#include <cstdlib>
#include <cstdio>
#include <queue>
using namespace std;
#define MAXN 1001
priority_queue<int , vector<int>, greater<int> > q;
char str[MAXN];
int huf[MAXN];
int n;
void solve()
{
int ans = 0, a, b;
while(q.size() != 1)
{
a = q.top(); q.pop();
b = q.top(); q.pop();
q.push(a+b);
ans += (a+b);
}
printf(ans <= n?"yes\n":"no\n");
}
void init()
{
while(!q.empty()) q.pop();
memset(huf, 0, sizeof(huf));
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
init();
scanf("%d", &n);
scanf("%s", str);
for(int i = 0; str[i]; i++)
{
huf[str[i]-'a']++;
}
for(int i = 0; i < 26; i++) if(huf[i])
{
q.push(huf[i]);
}
if(q.size() == 1)
{
int a = q.top(); q.pop();
printf(a <= n?"yes\n":"no\n");
continue;
}
solve();
}
return 0;
}