hdu2527 Huffman Coding

#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
char s[100005];
int t;
struct dian
{
    friend bool operator < (dian n1,dian n2)
     {
         return (n1.x>n2.x);
     }
     int node,l,r,x;
};
dian n[105],n1,n2;
int dfs(int no,int depth)
{
    if (n[no].l==-1) return(depth*n[no].x);
    else return(dfs(n[no].l,depth+1)+dfs(n[no].r,depth+1));
}
int main()
{
    int T,m,len,i,tt,sum,hash[105];
    priority_queue<dian>q;
    while (~scanf("%d",&T))
    while (T--)
    {
        scanf("%d",&m);
        getchar();
        memset(hash,0,sizeof(hash));
        scanf("%s",s); len=strlen(s);
        for (i=0;i<len;i++) hash[s[i]-'a']++;
        t=0;
        while (!q.empty()) q.pop();
        for (i=0;i<26;i++)
         if (hash[i]!=0)
         {
             t++;
             n[t].x=hash[i];
             n[t].node=t;
             n[t].l=n[t].r=-1;
             q.push(n[t]);
         }
        tt=t;
        while (q.size()!=1)
        {
            n1=q.top(); q.pop();
            n2=q.top(); q.pop();
            tt++;
            n[tt].x=n1.x+n2.x;
            n[tt].node=tt;
            n[tt].l=n1.node; n[tt].r=n2.node;
            q.push(n[tt]);
        }
        sum=dfs(tt,0);
//      for (i=1;i<=tt;i++) printf("%d %d %d %d\n",n[i].node,n[i].x,n[i].l,n[i].r);
//      printf("%d\n",sum);
        if ((sum<=m&&t!=1)||(t==1&&n[1].x<=m)) printf("yes\n");
        else printf("no\n");
    }
}

http://acm.hdu.edu.cn/showproblem.php?pid=2527

posted on 2014-07-16 14:37  xiao_xin  阅读(98)  评论(0编辑  收藏  举报

导航