堆
堆是一种有效的完全二叉树结构,常用于实现优先队列。最大堆和最小堆分别保证根节点为最大或最小元素,常用于排序、图算法和合并有序数据等问题
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
| #include <iostream> #include <algorithm> using namespace std;
const int N = 100010;
int n, m;
int h[N], cnt;
void down(int u) { int t = u; if (u * 2 <= cnt && h[u * 2] < h[t]) t = 2 * u; if (u * 2 + 1 <= cnt && h[u * 2 + 1] < h[t]) t = u * 2 + 1; if (u != t) { swap(h[u], h[t]); down(t); } }
int main() { cin >> n >> m; for (int i = 1; i <= n; i++) cin >> h[i]; cnt = n; for (int i = n / 2; i >= 1; i--) down(i); while(m--) { cout << h[1] << " "; h[1] = h[cnt--]; down(1); } return 0; }
|