838. 堆排序
输入一个长度为n的整数数列,从小到大输出前m小的数。
输入格式
第一行包含整数n和m。
第二行包含n个整数,表示整数数列。
输出格式
共一行,包含m个整数,表示整数数列中前m小的数。
数据范围
1≤m≤n≤1051≤m≤n≤105,
1≤数列中元素≤1091≤数列中元素≤109
输入样例:
5 3
4 5 1 3 2
输出样例:
1 2 3
#include <iostream>
#include <algorithm>
#include <cstring>
#include <map>
#include <cstdio>
#include <cmath>
#include <vector>
#include <queue>
using namespace std;
int n,a[300010],m,size;
void down(int x){
int t=x;
if(x*2<size&&a[x*2]<a[t]) t=2*x;
if(x*2+1<size&&a[x*2+1]<a[t]) t=x*2+1;
if(x!=t){
swap(a[x],a[t]);
down(t);}
}
int main(){
scanf("%d%d",&n,&m);
size=n;
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
for(int i=n/2;i;i--) down(i);
while(m--){
printf("%d ",a[1]);
a[1]=a[size];
size--;
down(1);
}
return 0;
}
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 1e5 + 10;
int hp[N], ph[N];
int h[N];
int size;
// “I x”,插入一个数x;
// “PM”,输出当前集合中的最小值;
// “DM”,删除当前集合中的最小值(当最小值不唯一时,删除最早插入的最小值);
// “D k”,删除第k个插入的数;
// “C k x”,修改第k个插入的数,将其变为x;
void heap_swap(int u, int v)
{
swap(ph[hp[u]], ph[hp[v]]);
swap(hp[u], hp[v]);
swap(h[u], h[v]);
}
void down(int u)
{
int t = u;
if (2*u <= size && h[2*u] < h[t]) t = 2*u;
if (2*u+1 <= size && h[2*u+1] < h[t]) t = 2*u+1;
if (t != u)
{
heap_swap(t, u);
down(t);
}
}
void up(int u)
{
while (u/2 && h[u] < h[u/2])
{
heap_swap(u, u/2);
u >>= 1;
}
}
int main()
{
int n;
scanf("%d", &n);
char op[3];
int a, b;
int m = 0;
while (n--)
{
scanf("%s", op);
if (!strcmp(op, "I")) //插入
{
scanf("%d", &a);
m++;
h[++size] = a, ph[m] = size, hp[size] = m;//ph存储第k个数所在的位置,hp存储在该位置上的数的k值
up(size);
}
else if (!strcmp(op, "PM")) printf("%d\n", h[1]);
else if (!strcmp(op, "DM"))
{
heap_swap(1, size);
size--;
down(1);
}
else if (!strcmp(op, "D"))
{
scanf("%d", &a);
int u = ph[a];
heap_swap(u, size);
size--;
up(u), down(u);
}
else
{
scanf("%d%d", &a, &b);
int u = ph[a];
h[u] = b;
up(u), down(u);
}
}
return 0;
}