• 寒假Day58:POJ1521-Entropy-哈夫曼树+优先队列


    题目链接:

     POJ - 1521

    题意:求哈夫曼树

    输出哈夫曼树的顶点值ans(ans如果为0就输出字符串的长度len)、ans*8、len/ans

    思路:

    优先队列即可

    AC代码:

    #include<stdio.h>
    #include<iostream>
    #include<string.h>
    #include<algorithm>
    #include<queue>
    using namespace std;
    #define inf 0x3f3f3f3f
    typedef long long ll;
    
    int a[10100];
    
    int main()
    {
        string s;
        while(cin>>s)
        {
            if(s=="END")
                break;
            memset(a,0,sizeof(a));
            int maxx=-1;
            priority_queue<int,vector<int>,greater<int> >Q;
            for(int i=0; i<s.length(); i++)
            {
    //            if(s[i]=='_')
    //                continue;
    //            a[s[i]-'A']++;
                a[s[i]-'A']++;
                maxx=max(maxx,(int)(s[i]-'A'));
            }
            for(int i=0; i<=maxx; i++)
            {
                if(a[i])
                    Q.push(a[i]);
            }
            int ans=0;
            while(Q.size()>=2)
                // while(!Q.empty())
            {
                int p=Q.top();
                Q.pop();
                int q=Q.top();
                Q.pop();
                int x=p+q;
                Q.push(x);
                ans+=x;
            }
            if(ans==0)
                ans=s.length();
            int len=8*s.length();
            double w=len*1.0/ans;
            printf("%d %d %.1f
    ",len,ans,w);
        }
        return 0;
    }

    哈夫曼树求树顶点的值的代码模板:

    #include<bits/stdc++.h>
    using namespace std;
    typedef long long ll;
    
    int main()
    {
        int n;
        cin>>n;
        priority_queue<int,vector<int>,greater<int> >Q;
        for(int i=1; i<=n; i++)
        {
            int x;
            cin>>x;
            Q.push(x);
        }
        int ans=0;
        while(Q.size()>=2)
        {
            int p=Q.top();
            Q.pop();
            int q=Q.top();
            Q.pop();
            int x=p+q;
            Q.push(x);
            ans+=x;
        }
        cout<<ans<<endl;
        return 0;
    }
  • 相关阅读:
    每日一题-mysql(持续更新)
    http面试问题集锦
    存储测试简析
    横向越权测试—安全漏洞
    性能数据的准备-Jmeter
    获取当天七天时间
    vue生命周期
    vue的全选与反选
    filter兼容问题
    Http与Https
  • 原文地址:https://www.cnblogs.com/OFSHK/p/12544649.html
Copyright © 2020-2023  润新知