zoukankan      html  css  js  c++  java
  • [JOBDU1172]哈夫曼树

    题目大意:
      给你一堆权值,求这些权值建成哈夫曼树后的WPL。

    思路:
      哈夫曼树的WPL等于各非叶子结点权值之和。
      所以直接贪心模拟构建哈夫曼树的过程。
      先把所有的权值放在一个堆中,然后每次取里面最小的两个数加到答案中,并将他们的和重新放到堆中。
      整个过程并不需要把树存下来。

     1 #include<cstdio>
     2 #include<cctype>
     3 #include<ext/pb_ds/priority_queue.hpp>
     4 inline int getint() {
     5     register char ch;
     6     while(!isdigit(ch=getchar()));
     7     register int x=ch^'0';
     8     while(isdigit(ch=getchar())) x=(((x<<2)+x)<<1)+(ch^'0');
     9     return x;
    10 }
    11 __gnu_pbds::priority_queue<int,std::greater<int> > q;
    12 int main() {
    13     int n;
    14     while(~scanf("%d",&n)) {
    15         q.clear();
    16         for(register int i=1;i<=n;i++) {
    17             q.push(getint());
    18         }
    19         int ans=0;
    20         for(register int i=1;i<n;i++) {
    21             int tmp=q.top();
    22             q.pop();
    23             tmp+=q.top();
    24             q.pop();
    25             ans+=tmp;
    26             q.push(tmp);
    27         }
    28         printf("%d
    ",ans);
    29     }
    30     return 0;
    31 }
  • 相关阅读:
    sdibt 1251 进化树问题
    hdu 2014 位运算
    poj 3254 状态压缩dp
    hdu 5040bfs+优先队列 需要存状态
    zoj 3812 状压dp
    C++标准库:bitset 用法整理&&zoj 3812
    BZOJ 2572 高速公路
    BZOJ 1036 树的统计
    BZOJ 1035 Risk
    BZOJ 1034 泡泡堂
  • 原文地址:https://www.cnblogs.com/skylee03/p/7656171.html
Copyright © 2011-2022 走看看