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

题目链接: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[N];
    char s[N];

    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

 

posted @ 2015-12-29 13:20  西瓜不懂柠檬的酸  Views(175)  Comments(0Edit  收藏  举报
levels of contents