我是靠谱客的博主 轻松未来,这篇文章主要介绍【POJ】优先队列的应用一、优先队列基本语法二、POJ两题,现在分享给大家,希望可以做个参考。

一、优先队列基本语法

1.定义

复制代码
1
2
3
4
5
6
7
8
#include<queue> #include<functional> #include<vector> //大顶堆 priority_queue<int> maxheap; //小顶堆 priority_queue<int, vector<int>, greater<int>> minheap;

2.函数

复制代码
1
2
3
4
5
6
maxheap.empty(); int t=maxheap.top(); maxheap.pop(); maxheap.push(5); maxheap.size();

二、POJ两题

1、Huffman编码树

http://algorithm.openjudge.cn/2020hw1/2D/
题目:计算最小树外部路径长度总和。
思路:使用优先队列,每次弹出两个最小的数a b,ans+=a+b,再把(a+b)入队,直到队空。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include<iostream> #include<cstring> #include<queue> #include<vector> #include<functional> using namespace std; priority_queue<int> maxheap; priority_queue<int, vector<int>, greater<int>> minheap; int main(){ int t, n; cin >> t; while (t--){ int ans = 0; while (!minheap.empty()) minheap.pop(); cin >> n; for (int i = 0; i < n; i++){ int temp; cin >> temp; minheap.push(temp); } while (!minheap.empty()){ int a = minheap.top(); minheap.pop(); if (minheap.empty()) break; int b = minheap.top(); minheap.pop(); ans += (a + b); minheap.push(a + b); } cout << ans << endl; } return 0; }

2、Dynamic Median(模拟堆)

http://algorithm.openjudge.cn/2020prefinaltest/C/

  • 题目:找数列中的中位数。
  • 思路:使用优先队列,模拟两个堆(e.g. 大顶堆:1,2,|小顶堆:3,4),保证左边的大顶堆元素个数永远比小顶堆多1或等于。则大顶堆的堆顶元素为中位数。
  • 注:读入字符时%c前加一个空格防止读入空格,否则一直不能ac…scanf(" %c", &c);
    插入数字前判断堆是否为空。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include<iostream> #include<cstring> #include<queue> #include<vector> #include<functional> using namespace std; priority_queue<int> maxheap; priority_queue<int, vector<int>, greater<int>> minheap; void query(){ printf("%dn", maxheap.top()); } void del(){ maxheap.pop(); if (maxheap.size() < minheap.size()){ int temp = minheap.top(); minheap.pop(); maxheap.push(temp); } } void insert(){ int temp; scanf("%d", &temp); if (maxheap.empty() || minheap.empty()){ maxheap.push(temp); } else{ if (temp > minheap.top()) minheap.push(temp); else maxheap.push(temp); } if (maxheap.size() == minheap.size() + 2){ temp = maxheap.top(); maxheap.pop(); minheap.push(temp); } if (maxheap.size() < minheap.size()){ int temp = minheap.top(); minheap.pop(); maxheap.push(temp); } } int main(){ int t, n; scanf("%d", &t); while (t--){ while (!minheap.empty()) minheap.pop(); while (!maxheap.empty()) maxheap.pop(); scanf("%d", &n); while (n--){ char c; scanf(" %c", &c); if (c == 'I') insert(); else if (c == 'Q') query(); else del(); } } return 0; }

最后

以上就是轻松未来最近收集整理的关于【POJ】优先队列的应用一、优先队列基本语法二、POJ两题的全部内容,更多相关【POJ】优先队列内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(79)

评论列表共有 0 条评论

立即
投稿
返回
顶部