[hihoCoder] 题外话·堆

简介: A direct applicatin of the heap data structure. Specifically, a max heap is used. The required functions include insertion of a node to the heap and extraction of the maximum element of the heap.

A direct applicatin of the heap data structure. Specifically, a max heap is used. The required functions include insertion of a node to the heap and extraction of the maximum element of the heap. Each time you insert or remove an element to or from the heap, you need to maintain the max heap property.

The code is as follows.

If you want to learn more about heap, you may refer to this passage.

 1 #include <iostream>
 2 #include <vector>
 3 
 4 using namespace std;
 5 
 6 class Heap {
 7 public:
 8     Heap() {
 9         data.clear();
10     }
11 
12     inline int parent(int idx) {
13         return (idx - 1) >> 1;
14     }
15 
16     inline int left(int idx) {
17         return (idx << 1) + 1;
18     }
19 
20     inline int right(int idx) {
21         return (idx << 1) + 2;
22     }
23 
24     void max_heapify(int idx) {
25         int largest = idx;
26         int l = left(idx), r = right(idx);
27         if (l < (int)data.size() && data[l] > data[largest]) largest = l;
28         if (r < (int)data.size() && data[r] > data[largest]) largest = r;
29         if (largest != idx) {
30             swap(data[idx], data[largest]);
31             max_heapify(largest);
32         }
33     }
34 
35     void insert(int elem) {
36         data.push_back(elem);
37         int idx = data.size() - 1;
38         while (idx >= 0 && parent(idx) >= 0 && data[parent(idx)] < data[idx]) {
39             swap(data[parent(idx)], data[idx]);
40             idx = parent(idx);
41         }
42     }
43 
44     int extract_max(void) {
45         int maximum = data[0];
46         swap(data[0], data[data.size() - 1]);
47         data.erase(data.end() - 1, data.end());
48         max_heapify(0);
49         return maximum;
50     }
51 
52 private:
53     vector<int> data;
54 };
55 
56 int main(void) {
57     int events;
58     while (scanf("%d", &events) != EOF) {
59         Heap sugars;
60         for (int i = 0; i < events; i++) {
61             char order[2];
62             scanf("%s", order);
63             if (order[0] == 'A') {
64                 int sugar;
65                 scanf("%d", &sugar);
66                 sugars.insert(sugar);
67             }
68             else printf("%d\n", sugars.extract_max());
69         }
70     }
71     return 0;
72 }
目录
相关文章
|
8月前
【每日一题Day361】LC2558从数量最多的堆取走礼物 | 大顶堆
【每日一题Day361】LC2558从数量最多的堆取走礼物 | 大顶堆
46 0
|
8月前
sdut 链表4
sdut 链表4
38 1
|
8月前
|
存储
面试题 03.03:堆盘子
面试题 03.03:堆盘子
44 0
|
8月前
面试题 08.13:堆箱子
面试题 08.13:堆箱子
66 0
|
存储 算法 Java
【朝花夕拾】Android性能篇之(三)Java内存回收
JVM提供了大量的垃圾收集器来完成内存的回收工作,采用了根搜索算法、分代算法等各种算法来实现垃圾回收。Java程序员为了更好地调优内存,并为了防止内存泄漏,必须对内存回收机制做一定的了解,并能合理使用强引用、软引用、弱引用。
1669 0

热门文章

最新文章

下一篇
开通oss服务