输入一个长度为 n 的整数数列,从小到大输出前 m 小的数。
#include <iostream> using namespace std; const int N = 1e5 + 10; int n, m, len; int h[N]; void down (int u) { int t = u; int l = u * 2, r = u * 2 + 1; if (l <= len && h[l] <= h[t]) t = l; if (r <= len && h[r] <= h[t]) t = r; if (t != u) { swap (h[t], h[u]); down (t); } } int main() { cin >> n >> m; len = n; for (int i = 1; i <= n; i++) cin >> h[i]; for (int i = n / 2; i; i--) down (i); while (m--) { cout << h[1] << " "; h[1] = h[len--]; down (1); } return 0; }
标签:cout,int,堆排序,len,down,-- From: https://www.cnblogs.com/leetothemoon/p/16945498.html