堆排序
题目
题解
#include <iostream>
using namespace std;
const int N = 100010;
int n, m;
int num[N], cou;
void down(int u)
{
int t = u;
if (u * 2 <= cou && num[u * 2] < num[t]) t = u * 2;
if (u * 2 + 1 <= cou && num[u * 2 + 1] < num[t]) t = u * 2 + 1;
if (u != t) {
swap(num[u], num[t]);
down(t);
}
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++ ) cin >> num[i];
cou = n;
for (int i = n / 2; i; i -- ) down(i);
while (m -- ) {
cout << num[1] << " ";
num[1] = num[cou -- ];
down(1);
}
return 0;
}
模拟堆
题目
题解
#include <iostream>
#include <string.h>
using namespace std;
const int N = 100010;
int n;
int m;
int cou;
int num[N];
int hp[N];
int ph[N];
void heap_swap(int a, int b)
{
swap(ph[hp[a]], ph[hp[b]]);
swap(hp[a], hp[b]);
swap(num[a], num[b]);
}
void down(int u) {
int t = u;
if (u * 2 <= cou && num[t] > num[u * 2]) t = u * 2;
if (u * 2 + 1 <= cou && num[t] > num[u * 2 + 1]) t = u * 2 + 1;
if (u != t) {
heap_swap(u, t);
down(t);
}
}
void up(int u) {
while (u / 2 && num[u] < num[u / 2]) {
heap_swap(u, u / 2);
u >>= 1;
}
}
int main()
{
cin >> n;
while (n -- ) {
int x, k;
char op[5];
cin >> op;
if (!strcmp(op, "I")) {
cin >> x;
cou ++ ;
m ++ ;
ph[m] = cou;
hp[cou] = m;
num[cou] = x;
up(cou);
}
else if (!strcmp(op, "PM")) cout << num[1] << endl;
else if (!strcmp(op, "DM")) {
heap_swap(1, cou);
cou -- ;
down(1);
}
else if (!strcmp(op, "D")) {
cin >> k;
k = ph[k];
heap_swap(k, cou);
cou -- ;
up(k);
down(k);
}
else {
cin >> k >> x;
k = ph[k];
num[k] = x;
up(k);
down(k);
}
}
return 0;
}