• 哈夫曼树


    離散數學學過的哈夫曼編碼,就是通過哈夫曼樹實現的,每次選擇權值最小的兩個節點,實現的是可變長的編碼的壓縮...不說了

    實現的話可以用優先隊列,比如下面這個題:

    poj 3253.Fence Repair

    這題的題意坑死我了,看懂之後才發現這麼合理...

     1 // poj 3253.Fence Repair
     2 // 堆排序 优先队列 
     3 // references:
     4 // ...
     5 /* 被题意坑死了,原来他的意思是在长度为L的木板上切割的代价是L,不管你切成怎么样,而不是切我需要的长度的费用!!! 
     6    所以在长度为21上切一次,代价就是21,然后切成什么样就需要用贪心了,若切成13+8,那么下一次切13分成8+5就ok了
     7    若切成16+5,下一次的代价就是16了...
     8    所以,你会做的就是切的越小越好(13<16),那么就是选择越小的相加越好,那么就是在优先队列中每次选头两个, bingo
     9 */
    10 #include <iostream>
    11 #include <cstring>
    12 #include <cstdio>
    13 #include <stack>
    14 #include <string>
    15 #include <vector>
    16 #include <queue>
    17 #include <algorithm>
    18 #include <set>
    19 
    20 using namespace std;
    21 
    22 long long a[200005];
    23 struct cmp
    24 {
    25     bool operator () (int x, int y)
    26     {
    27         return x > y;
    28     }
    29 };
    30 
    31 int main()
    32 {
    33     int n;
    34     while(scanf("%d", &n) != EOF)
    35     {
    36         priority_queue <int, vector<int>, cmp> q;
    37     
    38         long long sum=0;
    39         for(int i=0; i<n; i++)
    40         {
    41             cin >> a[i];
    42             sum += a[i];
    43             q.push(a[i]);
    44         }
    45         
    46             
    47         long long a, b, ans=sum;
    48         
    49         while(!q.empty())
    50         {
    51             a = q.top();
    52             q.pop();
    53             b = q.top();
    54             q.pop(); 
    55             
    56             if(a + b != sum)
    57             {
    58                 ans += a + b;
    59                 q.push(a+b);
    60             }
    61             else
    62                 break;
    63         }
    64         printf("%I64d
    ", ans);        //%lld->wa
    65     }
    66     
    67     
    68     
    69     return 0;
    70 }
  • 相关阅读:
    RocketMq(一、双master模式集群搭建)
    activeMQ(二、与springboot集成)
    activeMQ(一、基础练习)
    oracle分区【转载】
    oracle索引
    实习 | 第一天
    再学ajax--第二天 | 基于php+mysql+ajax的表单注册、登录、注销
    再学ajax--第一天
    ECMAScript6入门学习--第一天
    关于px、pt、em、rem四个单位的解释
  • 原文地址:https://www.cnblogs.com/dominjune/p/4720968.html
Copyright © 2020-2023  润新知