文章
1
粉丝
316
获赞
0
访问
7.7k
哈夫曼编码问题
每次从数组中挑选出最小的两个数,将这两个数加入到体力消耗值,并将这两个数相加的结果放入数组,至到取完所有的元素
本题的关键在于如何取数组中最小的两个数:
首先可以排除qsort()和sort(),因为这两个库函数的时间复杂度均为O(nlogn),然后还需要遍历数组,总的时间复杂度在O(n^2logn),稳稳地超时
因为每次只需要取出最小的两个数,所以可以考虑使用小顶堆:建堆的时间复杂度为O(n),每次调整堆的时间复杂度为O(logn),总的时间复杂度为O(n+logn)
使用C++的话,使用优先队列即可实现小顶堆的功能
使用C的话,我们需要手动建堆
附上C语言代码:
- #include <math.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define maxm (int)1e3
- #define maxn (int)1e6
- #define ms(a,b) memset(a,b,sizeof(a))
- int a[maxn];
- int n;
- int INF=(1<<31)-1;
- // 更改一个子树,使其变为小顶堆
- void up_lheap(int l,int r)
- {
- int father=l;
- int lson=l*2;
- int tmp=a[father];
- while(lson<=r)
- {
- if(a[lson]>a[lson+1]&&lson<r)
- lson++;
- if(tmp>a[lson])
- {
- a[father]=a[lson];
- father=lson;
- lson*=2;
- }
- else
- break;
- }
- a[father]=tmp;
- }
- // 得到一个完整的小顶堆
- void create_heap()
- ...
登录后发布评论
暂无评论,来抢沙发