题解 | #【模板】哈夫曼编码#

【模板】哈夫曼编码

https://www.nowcoder.com/practice/4c0419eb07c840ca8402e4f2a52cfd49

#include <functional>
#include <iostream>
#include <queue>
using namespace std;

int main() {
    int n;
    long long a;
    cin >> n;
    long long num1,num2;
    long long res= 0;
    priority_queue<long long,vector<long long>,greater<>> stack;
    while (cin >> a ) { // 注意 while 处理多个 case
        stack.push(a);
    }

    while( stack.size() >2 ){
        num1 = stack.top();
        stack.pop();
        num2 = stack.top();
        stack.pop();
        res+=(num1+num2);
        stack.push((num1+num2));
    }

    num1 = num1 = stack.top();
    stack.pop();
    num2 = stack.top();
    stack.pop();

    res+=(num1+num2);

    cout << res << endl;
    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

深夜书店vv:腾讯是这样的,去年很多走廊都加桌子当工区
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务