Hdu 2527 Safe Or Unsafe-哈夫曼编码+优先队列

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2527
#include <stdio.h>
#include <string.h>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include<stack>
#include<queue>
using namespace std;
char s[10010];
int haf[10010];
int T;
int n;
struct cmp
{
	bool operator ()(int &a,int &b)
	{
		return a>b;//最小值优先
	}	
};

priority_queue<int,vector<int>,cmp>q;

void init()
{
	int i;
	while(!q.empty())
		q.pop();
		
	memset(haf,0,sizeof(haf));
		for(i=0;i<strlen(s);i++)
		{
			haf[s[i]-'a']++;
		}
		for(i=0;i<26;i++)
		{
			if(haf[i])
			  q.push(haf[i]);
		}
	
}
void Haffman()
{
	int a,b;
	int sum=0;
	while(q.size()!=1)
	{
		a=q.top();
		q.pop();
		b=q.top();
		q.pop();
		sum+=(a+b);
		q.push(a+b);
	}
	printf(sum<=n?"yes\n":"no\n");
}
int main()
{
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d",&n);
		scanf("%s",s);
		init();
		if(q.size()==1)
		{
			int x=q.top();
			q.pop();
			printf(x<=n?"yes\n":"no\n");
		//	continue;
		}
		else
	    Haffman();
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值