您的位置:首页 > Web前端

Safe Or Unsafe--hdu2527(哈夫曼树求WPL)

2015-12-29 13:20 344 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2527

用优先队列模拟

#include<iostream>
#include<stdio.h>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
#define N 1100
#define met(a, b) memset(a, b, sizeof(a))

struct node
{
int x;

friend bool operator<(node a, node b)///优先队列,实质是堆;
{
return a.x > b.x;
}
};

int main()
{
int T, n;
int cnt
;
char s
;

scanf("%d", &T);

while(T--)
{
met(s, 0);
met(cnt, 0);

scanf("%d", &n);
scanf("%s", s);

int len = strlen(s);
for(int i=0; i<len; i++)
cnt[s[i]-'a']++;

priority_queue<node> Q;

node p, q;

for(int i=0; i<26; i++)
{
p.x = cnt[i];
if(cnt[i])
Q.push(p);
}

int ans = 0 ;

if(Q.size()==1)///如果只有一个元素WPL是本身;
ans = Q.top().x;

while(Q.size()!=1)
{
node min1 = Q.top(); Q.pop();///找到两个权值最小的,构成新的节点
node min2 = Q.top(); Q.pop();

q.x = min1.x + min2.x; Q.push(q);

ans += q.x;
}
/// printf("%d\n", ans);
printf(ans <= n ? "yes\n":"no\n");
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: