维护一个完全二叉树.
这个是一个小根堆的实现
#include
#include
#include
#define maxn 200
using namespace std;
int arr[maxn];
void upAdjuest(int a[], int pos) {
int temp = a[pos];
int j = (pos - 1) / 2;
while(j >= 0 && pos != 0) {
if(a[j] <= temp)
break;
a[pos] = a[j];
pos = j;
j = (pos -1) / 2;
}
a[pos] = temp;
}
void downAdjuest(int a[], int pos, int n) {
int temp = a[pos];
int j = pos * 2 + 1;
while(j <= n) {
if(j + 1 < n && a[j + 1] < a[j]) ++j;
if(temp <= a[j]) break;
a[pos] = a[j];
pos = j;
j = pos * 2 + 1;
}
a[pos] = temp;
}
void put(int a[], int value, int n) {
a[n] = value;
upAdjuest(a,n);
}
int deleteElem(int a[], int n) {
int temp = a[0];
swap(a[0],a[n]);
downAdjuest(a, 0, n - 1);
return temp;
}
int main() {
freopen("in.txt","r",stdin);
int value;
for(int i = 0;i<= 20;i++) {
scanf("%d",&value);
put(arr, value, i);
}
for(int i = 20;i>= 0;i--) {
if( i == 2) {
int a = 0;
}
printf("%d ",deleteElem(arr,i));
}
printf("\n");
return 0;
}