看题:
P3378 【模板】堆
题目描述
给定一个数列,初始为空,请支持下面三种操作:
- 给定一个整数 x x x,请将 x x x 加入到数列中。
- 输出数列中最小的数。
- 删除数列中最小的数(如果有多个数最小,只删除 1 1 1 个)。
输入格式
第一行是一个整数,表示操作的次数
n
n
n。
接下来
n
n
n 行,每行表示一次操作。每行首先有一个整数
o
p
op
op 表示操作类型。
- 若 o p = 1 op = 1 op=1,则后面有一个整数 x x x,表示要将 x x x 加入数列。
- 若 o p = 2 op = 2 op=2,则表示要求输出数列中的最小数。
- 若 o p = 3 op = 3 op=3,则表示删除数列中的最小数。如果有多个数最小,只删除 1 1 1 个。
输出格式
对于每个操作 2 2 2,输出一行一个整数表示答案。
样例 #1
样例输入 #1
5
1 2
1 5
2
3
2
样例输出 #1
2
5
提示
【数据规模与约定】
- 对于 30 % 30\% 30% 的数据,保证 n ≤ 15 n \leq 15 n≤15。
- 对于 70 % 70\% 70% 的数据,保证 n ≤ 1 0 4 n \leq 10^4 n≤104。
- 对于 100 % 100\% 100% 的数据,保证 1 ≤ n ≤ 1 0 6 1 \leq n \leq 10^6 1≤n≤106, 1 ≤ x < 2 31 1 \leq x \lt 2^{31} 1≤x<231, o p ∈ { 1 , 2 , 3 } op \in \{1, 2, 3\} op∈{1,2,3}。
题解
所有图片来自这里。
我们可以使用小根堆来做这题
小根堆1 ↓

插入
首先++len
heap[++len] = n;
然后for循环排序
for (int i = len; i / 2 >= 1 && heap[i] < heap[i / 2]; i /= 2) {
swap(heap[i], heap[i / 2]);
}
最后合成push函数
void push(int n, int &len, vector<int> &heap) {
heap[++len] = n;
for (int i = len; i / 2 >= 1 && heap[i] < heap[i / 2]; i /= 2) {
swap(heap[i], heap[i / 2]);
}
}
删除
首先把第一个变为最后一个

然后删除最后一个
while (2 * t <= len) {
int son = 2 * t;
if (son + 1 <= len && heap[son + 1] < heap[son]) {
++son;
}
if (heap[t] > heap[son]) {
swap(heap[t], heap[son]);
t = son;
} else {
break;
}
}
最后合成pop函数
void pop(int &len, vector<int> &heap) {
heap[1] = heap[len--];
int t = 1;
while (2 * t <= len) {
int son = 2 * t;
if (son + 1 <= len && heap[son + 1] < heap[son]) {
++son;
}
if (heap[t] > heap[son]) {
swap(heap[t], heap[son]);
t = son;
} else {
break;
}
}
}
主函数
我们先建好变量、数组
int n;
cin >> n;
int len = 0;
vector<int> heap(N);
然后for循环
for (int i = 0; i < n; ++i){
int op;
cin >> op;
if (op == 1) {
int x;
cin >> x;
push(x, len, heap);
}
if (op == 2) {
cout << heap[1] << endl;
}
if (op == 3) {
pop(len, heap);
}
}
最终代码
#include <iostream>
#include <vector>
using namespace std;
const int N = 1000010;
void push(int n, int &len, vector<int> &heap);
void pop(int &len, vector<int> &heap);
int main() {
int n;
cin >> n;
int len = 0;
vector<int> heap(N);
for (int i = 0; i < n; ++i){
int op;
cin >> op;
if (op == 1) {
int x;
cin >> x;
push(x, len, heap);
}
if (op == 2) {
cout << heap[1] << endl;
}
if (op == 3) {
pop(len, heap);
}
}
return 0;
}
void push(int n, int &len, vector<int> &heap) {
heap[++len] = n;
for (int i = len; i / 2 >= 1 && heap[i] < heap[i / 2]; i /= 2) {
swap(heap[i], heap[i / 2]);
}
}
void pop(int &len, vector<int> &heap) {
heap[1] = heap[len--];
int t = 1;
while (2 * t <= len) {
int son = 2 * t;
if (son + 1 <= len && heap[son + 1] < heap[son]) {
++son;
}
if (heap[t] > heap[son]) {
swap(heap[t], heap[son]);
t = son;
} else {
break;
}
}
}
左节点和右节点都比根节点小 ↩︎

355

被折叠的 条评论
为什么被折叠?



